反转字符串
中间变量交换
class Solution { public: void reverseString(vector<char>& s) { char temp; for(int i=0 ;i<s.size()/2;i++) { temp = s[i]; s[i] = s[s.size()-1 - i]; s[s.size()-1 - i] = temp; } } };
使用对调函数
void reverseString(vector<char>& s) { for (int i = 0, j = s.size() - 1; i < s.size()/2; i++, j--) { swap(s[i],s[j]); } }
使用反转库函数
class Solution { public: void reverseString(vector<char>& s) { reverse(s.begin(),s.end()); } };
二刷
class Solution { public: void reverseString(vector<char>& s) { char tmp; int left=0 ,right=s.size()-1; while(left<right) { tmp = s[right]; s[right] = s[left]; s[left] = tmp; left++; right--; } return ; } };