344-Reverse-String
Problem:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
One possible Solution:
char* reverseString(char* s) { int i,j,k; char c; k=0; while(*(s+k)!='\0') k++; for(i=0,j=k-1;i<=j;i++,j++){ c=*(s+i); *(s+i)=*(s+j); *(s+j)=c; } return s; }
Puzzle:
I have successfully runed the program on my Laptop Computer with gcc4.8.4 in Ubuntu14.04.1 environment. However, the Leetcode website reports "RUNTIME ERROR" 。
Does anyone know the reason?
Answer: the index "j++" should be "j--".
char* reverseString(char* s) { int i,j,k; char c; k=0; while(*(s+k)!='\0') k++; for(i=0,j=k-1;i<=j;i++,j--){ c=*(s+i); *(s+i)=*(s+j); *(s+j)=c; } return s; }
Addition:
The solution above may be not a good way to solve the problem, especially if the size of the string is too large, for an example, larger than the size of cache line or large than the size of a page.
A better way:
char* reverseString(char* s) { int i,j,k; char c; k=0; //while(*(s+k)!='\0') // k++; k=strlen(s); for(i=0,j=k-1;i<=j;i++,j--){ c=*(s+i); *(s+i)=*(s+j); *(s+j)=c; } return s; }