「代码随想录算法训练营」第八天 | 字符串 part2

151. 反转字符串中的单词

题目链接:https://leetcode.cn/problems/reverse-words-in-a-string/
题目难度:中等
文章讲解:https://programmercarl.com/0151.翻转字符串里的单词.html
视频讲解: https://www.bilibili.com/video/BV1uT41177fX
题目状态:修改后过

个人思路:
讨了个巧,使用istringstream分割字符串,在将分割出来的单词依次存放到一个vector<string>里面,最后翻转vector<string>并通过ostringstream将结果输出。

实现代码:

class Solution {
public:
    string reverseWords(string s) {
        istringstream iss(s);
        vector<string> words;
        string word;
        while(iss >> word) {
            words.push_back(word);
        }
        reverse(words.begin(), words.end());
        ostringstream oss;
        for(int i = 0; i < words.size(); ++i) {
            if(i != 0) oss << " ";
            oss << words[i];
        }
        return oss.str();
    }
};

55. 右旋字符串(卡码网

题目链接:https://kamacoder.com/problempage.php?pid=1065
文章讲解:https://programmercarl.com/kama55.右旋字符串.html
题目状态:过

个人思路:
创建一个新string类型的res用来存放结果,首先先将字符串后n个元素加入res,再将剩下的元素加入到res

实现代码:

#include <iostream>
#include <string>

using namespace std;
using std::string;

int main() {
    int n;
    string s;
    cin >> n >> s;
    string res;
    int sLen = s.size();
    for(int i = sLen - n; i < sLen; ++i) {
        res += s[i];
    }
    for(int i = 0; i < sLen - n; ++i) {
        res += s[i];
    }
    cout << res << endl;
    return 0;
}

热门相关:新闻女王粤语   我真不是开玩笑   春秋我为王   一世倾心:误惹腹黑师弟   换命真相粤语   婚婚欲醉:腹黑老公萌宠妻