码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-917-Reverse Only Letters]

时间:2018-10-07 14:43:57      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:nts   only   color   hat   ring   continue   and   tar   contain   

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 "

思路:

两个标记,分别从前和从后往中间方向遍历,遇到字母交换,否则游标继续往下走。

bool isLetter(char ch)
{
    return ((ch >= a && ch <= z) || (ch >= A && ch <= Z));
}
string reverseOnlyLetters(string S)
{
    string ret = S;
    int n = S.length();
    int start = 0;
    int end = n - 1;
    while(start <= n-1 && end >= 0)
    {
        if(!isLetter(S[end])){end--;continue;}
        if(!isLetter(ret[start])){start++;continue;}
        ret[start++] = S[end--];
    } 
    return ret;       
}

 

[leetcode-917-Reverse Only Letters]

标签:nts   only   color   hat   ring   continue   and   tar   contain   

原文地址:https://www.cnblogs.com/hellowooorld/p/9749986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!