题解 | #字符串变形#

字符串变形

https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e

class Solution {
  public:
    string transStr(string s) {
        string str = "";
        for (char& x : s) {
            if (x >= 'a' && x <= 'z') {
                x = char(x - 32);
            } else if (x >= 'A' && x <= 'Z') {
                x = char(x + 32);
            }
            str += x;
        }
        return str;
    }

    string trans(string s, int n) {
        stack<string> arr;
        string str = "";
        if (s.empty()) {
            return str;
        }

        for (int i = 0; i <= n; i++) { 
            if (i == n || s[i] == ' ') {
                if (!str.empty()) { 
                    str = transStr(str);
                    arr.push(str);
                    str.clear();
                }
                if (i < n) { 
                    arr.push(" ");
                }
            } else {
                str += s[i];
            }
        }

        str.clear();
        while (!arr.empty()) {
            str += arr.top();
            arr.pop();
        }
        return str;
    }
};

全部评论

相关推荐

03-26 15:18
已编辑
华北水利水电大学 Java
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务