THE
problem
achieve
Ideas
In this question, seeing the concept of reversal, left and right, we must want dichotomy and left and right double pointers. Since it is not a sorting issue, consider the left and right double pointers. Just apply the basic left and right pointer template.
- define left right
- get mid
-
- while left >= mid
-
- swap ;
- return
Summary and reflection
- Note the boundary problem solved in mid = (0+ size())/2 and while(left<right). Together, they can handle arrays of singular or even length. The principle is easy to derive by pushing it by yourself.
Code
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size();
int mid = (left+right)/2;// pay attention into whether mid is correct.
while(left<right){
swap(s,left,right);
left++;
right--;
}
}
void swap(vector<char> &s,int left,int right){
char temp = '\0';
temp = s[left];
s[left] = s[right-1];
s[right-1] = temp;
}
};