【leetcode】917. Reverse Only Letters(双指针)
Given a string s, reverse the string according to the following rules:
- All the characters that are not English letters remain in the same position.
- All the English letters (lowercase or uppercase) should be reversed.
class Solution { public: string reverseOnlyLetters(string s) { //用栈或者双指针即可 //two-pointer int n=s.size(); int left=0,right=n-1; while(left<right) { //这样写是错误的:~((s[left]>='A'&&s[left]<='Z')||(s[left]>='a'&&s[left]<='z') 按位取反以及逻辑取非不一样 //写法和快排思路相似 while(left<right && !((s[left]>='A'&&s[left]<='Z')||(s[left]>='a'&&s[left]<='z'))) { //cout<<~((s[left]>='A'&&s[left]<='Z')||(s[left]>='a'&&s[left]<='z'))<<endl; left++; } cout<<left<<endl; while(left<right && !((s[right]>='A'&&s[right]<='Z')||(s[right]>='a'&&s[right]<='z'))) { right--; } //cout<<left<<"-"<<right<<endl; if(left<right) { //cout<<left<<"-"<<right<<endl; char tmp=s[left]; s[left]=s[right]; s[right]=tmp; left++; right--; } } return s; } };