URL:https://www.lintcode.com/problem/reverse-string/description
描述
写一个方法,接受给定字符串作为输入,返回将这个字符串逐个字符翻转后的新字符串。
您在真实的面试中是否遇到过这个题?
样例
样例 1:
输入:"hello"
输出:"olleh"
样例 2:
输入:"hello world"
输出:"dlrow olleh"
(1)通过率:42%
在代码段中添加:
int n = s.size();
char temp;
for (int i = 0; i < n/2; i++) {
if(s[i]==s[n-i-1])
continue;
else
swap(s[i],s[n-i-1]);
}
return s;
即可:
原因,在遇见转义字符时,会将‘\字符’反转为‘字符\’,题目中对这种字符是不进行反转的。
(2)通过率:100%
在代码段中添加:
'\\'是转义字符你也可以写成ASCll码(\的ASCll码为92):
更多的ASCll码知识点请参考:C语言变量类型及其表示范围
string lcc;
int n = s.size();
for (int i = n-1; i >=0; i--) {
/* code */
if(s[i-1]!='\\'){
lcc+=s[i];
}else{
lcc+='\\';
lcc+=s[i];
i--;
}
}
return lcc;
即可: