本日任务很重,加油。
151.翻转字符串里的单词
class Solution {
public:
void reverse(string& s, int start, int end){
while(end > start){
swap(s[end], s[start]);
end--;
start++;
}
}
string reverseWords(string s){
int n = s.size();
int left = 0, right = n - 1;
// 去除开始的空格
while(left <n && s[left] == ' '){
left++;
}
// 去除最后的空格
while(right >= 0 && s[right] == ' '){
right--;
}
int new_index = 0;
for(int i = left; i <= right; i++){
if(i > 0 && s[i] == s[i - 1] && s[i] == ' '){
continue;
}else{
s[new_index++] = s[i];
}
}
s.resize(new_index);
n = s.size();
reverse(s, 0, n - 1);
for(int start = 0, end = 0; end < n; end++){
if(s[end] == ' '){
reverse(s, start, end - 1);
start = end + 1;
}
if(end == n - 1){
reverse(s, start, end);
}
}
return s;
}
};
55.右旋转字符串
55. 右旋字符串(第八期模拟笔试) (kamacoder.com)
#include<iostream>
#include<algorithm>
using namespace std;
void reverse_str(string& s, int start, int end){
while(start < end){
swap(s[start], s[end]);
start++;
end--;
}
}
int main(){
string s;
int k;
cin >> s;
cin >> k;
int n = s.size();
reverse_str(s, 0, n - 1);
reverse_str(s, 0, k - 1);
reverse_str(s, k, n - 1);
cout << s << endl;
return 0;
}
28. 实现 strStr()
28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
kmp 懂得都懂,太难了。
class Solution {
public:
vector<int> getNext(string needle){
int n = needle.size(), prehead = 0;
vector<int> next;
next.push_back(0);
for(int i = 1; i < n; i++){
while(needle[i] != needle[prehead]){
if(prehead == 0){
break;
}else{
prehead = next[prehead - 1];
}
}
if(needle[i] == needle[prehead]) prehead++;
next.push_back(prehead);
}
return next;
}
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
vector<int> next = getNext(needle);
for(int i = 0, j = 0; i < n; i++){
while(j > 0 && haystack[i] != needle[j]) j = next[j - 1];
if(haystack[i] == needle[j]) j++;
if(j == m) return i - j + 1;
}
return -1;
}
};
459.重复的子字符串
class Solution {
public:
vector<int> getNext(string s){
vector<int> next;
next.push_back(0);
int j = 0, n = s.size();
for(int i = 1; i < n; i++){
while(j > 0 && s[i] != s[j]) j = next[j - 1];
if(s[i] == s[j]) j++;
next.push_back(j);
}
return next;
}
bool repeatedSubstringPattern(string s) {
vector<int> next = getNext(s);
string t = s + s;
int j = 0, n = t.size();
// for(int i = 1; i < n - 1; i++){
// while(j > 0 && t[i] != s[j]) j = next[j - 1];
// if(t[i] == s[j]) j++;
// if(j == n / 2) return true;
// }
return next[n / 2 - 1] != 0 && n / 2 % (n / 2 - next[n / 2 - 1]) == 0;
}
};

被折叠的 条评论
为什么被折叠?



