917. Reverse Only Letters

Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

 

Note:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122 
  3. S doesn't contain \ or "

只翻转英文字母。

#include<vector>
#include <cstdlib>
#include<iostream>
#include <unordered_set>
#include <algorithm>
#include<string>

using namespace std;

class Solution {
public:
    string reverseOnlyLetters(string S) {
        int n = S.size();
        int i = 0, j = n - 1;
        while (i < j) {
            while (!isalpha(S[i]) && i < j)
                i++;
            while (!isalpha(S[j]) && j > i)
                j--;
            //std::cout << "S[i] " << S[i] << " S[j] " << S[j] << endl;
//            char tmp = S[i];
//            S[i] = S[j];
//            S[j] = tmp;
            swap(S[i], S[j]);
            i++, j--;

        }
        return S;
    }
};

int main() {
    string S = "Test1ng-Leet=code-Q!";
    Solution solution;
    std::cout << solution.reverseOnlyLetters(S) << std::endl;
    return 0;
}

 

Your runtime beats 100.00 % of cpp submissions

posted @ 2018-10-14 20:26  hopskin1  阅读(151)  评论(0编辑  收藏  举报