题解 | 字符串变形

字符串变形

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

#include <cstddef>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @param n int整型
     * @return string字符串
     */
    string trans(string s, int n) {
        // write code here
        //思路:需要做两个操作。先调整所有字母的大小写,再反序每个单词的位置
        if (n == 0) return nullptr; //空字符串则不处理
        stack<string> mystack;
        string str;
        int pos = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] >= 'a' && s[i] <= 'z') //如果是小写字母就转换为大写字母
                s[i] = s[i] - 32;
            else if (s[i] >= 'A' && s[i] <= 'Z')
                s[i] = s[i] + 32;
            if (s[i] == ' ') {
                //遇到空格,将空格前的一个字符串单词截取出来放入栈中
                mystack.push(s.substr(pos, i - pos));
                mystack.push(" ");
                pos = i + 1;
            }
            if (i == n - 1)
                mystack.push(s.substr(pos, i - pos + 1));
        }
        while (!mystack.empty()) {
            str += mystack.top();
            mystack.pop();
        }
        return str;
    }
};

全部评论

相关推荐

弦五Strings:他之所以会举报你代课是因为在这种人眼里正常上课就是正义代课就是邪恶,典型二极管思维,处理方法就是私下沟通,你就说你自己家里经济困难或者家里父母生病什么之类的,需要去打工挣钱,用尽孝的正义对冲他认为的上课的正义,他可能就妥协了。
我的实习日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务