Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
void inverse(int start, int end, char *p)
{
char temp;
if(p)
{
temp=p[start];
p[start]=p[end];
p[end]=temp;
return;
}
else
{
return;
}
}
char* reverseString(char* s)
{
int length=strlen(s);
printf("%d\n",length);
if(!s)
{
return NULL;
}
int start;
int end;
start=0;
end=length-1;
while(start<end)
{
//char *p=s+start;
inverse(start,end,s); //这边犯了个错误,将 p作为参数传入,p地址偏移后,end的计数就应该也要减1,正确应该直接将S传入
//printf("%c",s[start]);
start++;
end--;
//printf("%s\n",s);
}
return s;
}
recursive way
class Solution(object):
def reverseString(self, s):
l = len(s)
if l < 2:
return s
return self.reverseString(s[l/2:]) + self.reverseString(s[:l/2])
classic way
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
if s==None:
return s
s1=0
e1=len(s)-1
while s1<e1:
tmp=s[s1] #may use s[s1],s[e1]=s[e1],s[s1], save one variable
s[s1]=s[e1]
s[e1]=tmp
s1=s1+1
e1=e1-1
return s
pythonic way
return s[::-1]