「代码随想录算法训练营」第八天 | 字符串 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;
}