今日任务
151. 反转字符串中的单词
- 题目链接: https://leetcode.cn/problems/reverse-words-in-a-string/description/
- 题目描述:
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1: 输入: “the sky is blue” 输出: “blue is sky the”
示例 2: 输入: " hello world! " 输出: “world! hello” 解释:
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。示例 3: 输入: “a good example” 输出: “example good a” 解释:
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个
Solution
class Solution {
public:
string reverseWords(string s) {
string ans = "";
int len = 0;
int pos = s.size() - 1;
bool is_first = true;
while(pos >= 0){
if(s[pos] == ' '){
if(len > 0){
if(!is_first){
ans += " ";
}
ans += s.substr(pos + 1, len);
is_first = false;
}
len = 0;
}else{
len++;
}
pos--;
}
if(len > 0){
if(!is_first){
ans += " ";
}
ans += s.substr(pos + 1, len);
}
return ans;
}
};
55. 右旋字符串(第八期模拟笔试)
- 题目链接: https://kamacoder.com/problempage.php?pid=1065
- 题目描述:
字符串的右旋转操作是把字符串尾部的若干个字符转移到字符串的前面。给定一个字符串 s 和一个正整数 k,请编写一个函数,将字符串中的后面 k
个字符移到字符串的前面,实现字符串的右旋转操作。例如,对于输入字符串 “abcdefg” 和整数 2,函数应该将其转换为 “fgabcde”。
输入:输入共包含两行,第一行为一个正整数 k,代表右旋转的位数。第二行为字符串 s,代表需要旋转的字符串。
输出:输出共一行,为进行了右旋转操作后的字符串。
样例输入:
2 abcdefg
样例输出:fgabcde
数据范围:1 <= k < 10000, 1 <= s.length < 10000;
Solution 整体反转 + 局部反转
#include <iostream>
#include <string>
#include <algorithm>
using std::cin, std::cout, std::endl, std::string;
int main(){
int n;
string s;
cin >> n >> s;
// cout << s.substr(s.size() - n) << s.substr(0, s.size() - n) <<endl;
reverse(s.begin(), s.end());
reverse(s.begin(), s.begin() + n);
reverse(s.begin() + n, s.end());
cout << s << endl;
return 0;
}
TODO
- KMP + Z Algorithm
- LeetCode周赛
- 上周卡码网比赛整理