Skip to content

Instantly share code, notes, and snippets.

@FionaT
Created April 5, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FionaT/a428c955bb145320ac0d to your computer and use it in GitHub Desktop.
Save FionaT/a428c955bb145320ac0d to your computer and use it in GitHub Desktop.
careercup 1.2
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
/*
[question]
1.2 Implement a function void reverse(char* str) in C or C++ which reverses a nullterminated string.
[solution]
use two pointers, one in the head another in the tail,
exchange the head and the tail element, head++ tail--
until when tail is smaller or euqal to head, then the loop can stop
[time complexity]
O(n)
scan every char in the string
[space complexity]
O(1)
we do this in place, so no extra space
[gist link]
[test case]
*/
void reverse_str(char *str)
{
int len = 0;
char *p = str, temp;
while(*p != NULL){
p++;
len++;
}
for(int i = 0, j = len - 1; i < j; i++, j--){
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main()
{
char str[] = "";
reverse_str(str);
cout<<str<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment