lc 翻转字符串里的单词

链接:https://leetcode-cn.com/explore/interview/card/bytedance/242/string/1011/

代码:

class Solution {
public:
    string reverseWords(string s) {
        int len = s.size();
        string res = "";
        string a[10000];
        int cnt = 0;
        int i = 0;
        while(i < len) {
            if(s[i] == ' ') {
                i++;
                continue;
            }
            string temp = "";
            while(i < len && s[i] != ' ') {
                temp += s[i];
                i++;
            }
            // cout << temp << endl;
            a[cnt] = temp;
            cnt++;
        }
        // for(int i = 0; i < cnt; i++) {
        //     cout << a[i] << endl;
        // }
        if(cnt == 1) return a[0];
        // cout << "=====" << endl;
        for(int i = cnt-1; i >= 0; i--) {
            if(i == cnt-1) res += a[i];
            else {
                res += " ";
                res += a[i];
            }
        }
        return res;
    }
};
View Code

思路:normalize 掉空格,存到栈中逆序输出。

猜你喜欢

转载自www.cnblogs.com/FriskyPuppy/p/12907858.html
今日推荐