1. 程式人生 > 其它 >【leetcode】雙指標 917. Reverse Only Letters

【leetcode】雙指標 917. Reverse Only Letters

Given a strings, 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; } };