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.

这题就是字符串首位交换的题目,只是碰到非字母跳过即可。

class Solution {
public:
    static int Test() {
        auto res = Main("ab-cd");
        return 0;
    }
   static  bool isLetter(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }
    static string Main(string S) {
        int fi = 0, li = S.length() - 1;
        while (fi < li) {
            if (!isLetter(S[fi])) {
                fi++;
                continue;
            }
            while (li >= 0 && !isLetter(S[li])) {
                li--;
            }
            if (li <= fi) {
                break;
            }
            std::swap(S[fi], S[li]);
            fi++;
            li--;
        }
        return S;
    }
};

共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day