C Solution

• ``````char* reverseString(char* s) {
int sl=strlen(s);
char r[sl+1];
int i;
for(i=0;i<sl;i++){
r[sl-i-1]=*(s+i);
}
r[i]='\0';
strcpy(s,r);
return s;
}
``````

• @nanosheep What are you doing here? You actually can just reverse it in-place way as follows.

``````class Solution {
public:
string reverseString(string s)
{
int len = s.length();
for(int i = 0; i < len/2; ++i)
swap(s[i], s[len-i-1]);
return s;
}
};
``````

• I am quiet confuse why my answer is not correct?
#include <stdio.h>
#include <string.h>

String reverseString(){
int i, n;
char s[100];
char p[100];
//char s[100];
printf("Enter a String\n");
gets(s);
n = strlen(s);
//char s[] = "hello";
for(i=0;i<n;i++)
p[n-i-1]=s[i];
printf("%s\n",p);
return 0;
}

• @JobHunter1993 Could just format your code properly? before asking for help? thanks

• @LHearen Thanks for your suggestion, it's a better way that can reduce half of loop times and do not need another array space.
after revise:

``````char* reverseString(char* s) {
int sl = strlen(s);
char tmp;
if(sl==0){
return s;
}
int i;
for( i=0;i<sl/2;i++){
tmp=*(s+i);
*(s+i)=*(s+sl-i-1);
*(s+sl-i-1)=tmp;
}
return s;
}
``````

• @nanosheep Yes, right there! It's much better now.

• @JobHunter1993 said in C Solution:

String reverseString(){
int i, n;
char s[100];
char p[100];
//char s[100];
printf("Enter a String\n");
gets(s);
n = strlen(s);
//char s[] = "hello";
for(i=0;i<n;i++)
p[n-i-1]=s[i];
printf("%s\n",p);
return 0;
}

@JobHunter1993
Hi, I assume you return variable "p" in your function reverseString.
This will get garbage return, Cause "p" is a local pointer variable. And the local pointer variable will be eliminated after the function return.

So, do not try to return the local pointer variable in the function.

In your case, you should copy p to s, and return s.

Hope it will help.

• @LHearen
It's in C style, actually, it also doesn't make trivial duplicate, the implement of swap is using std::move,both are equivalent.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.