344. Reverse String(C++)
344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
题目大意:
字符串倒置。
解题方法:
第一个字符与最后一个非空字符对换。
注意事项:
1.字符串最后一个字符是空字符。
C++代码:
1.不良代码:
1 class Solution { 2 public: 3 string reverseString(string s) { 4 char *f,*e; 5 char temp; 6 f=&s[0]; 7 e=&s[s.length()-1]; 8 while(f!=e&f!=&s[s.length()/2]) 9 { 10 temp=*f; 11 *f=*e; 12 *e=temp; 13 f++; 14 e--; 15 } 16 return s; 17 } 18 };
2.改进后的代码:
1 class Solution { 2 public: 3 string reverseString(string s) { 4 for(int i=0,j=s.size()-1;i<j&&i!=j;i++,j--) 5 { 6 swap(s[i],s[j]); 7 } 8 return s; 9 } 10 };
-------------------------------------------------------------------转账请注明出处。
--------------------------------------------------------------------如有好的建议或错误,请指出。