参考资料:代码随想录 (programmercarl.com)
151.翻转字符串里的单词
对空格把控不行。
class Solution {
public:
void reverse(string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
void removeSapce(string &s) {
int slow = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] != ' ') {
if (slow != 0) {
s[slow] = ' ';
slow++;
}
while (i < s.size() && s[i] !=' ') {
s[slow] = s[i];
slow++;
i++;
}
}
}
s.resize(slow);
}
string reverseWords(string s) {
removeSapce(s);
reverse(s, 0, s.size() -1);
int k = 0;
for (int i = 0; i <= s.size(); i++) {
if (i == s.size()|| s[i] == ' ') {
reverse(s, k, i - 1);
k = i + 1;
}
}
return s;
}
};
卡码网:55.右旋转字符串
在翻转字符串里的单词的基础上,知道应该先整体翻转,再局部翻转。
#include<bits/stdc++.h>
using namespace std;
void reverse(string &s, int start, int end){
for (int i = start, j = end; i<j; i++, j--){
swap(s[i], s[j]);
}
}
int main(){
int k;
string s;
cin >> k;
cin >> s;
reverse(s.begin(), s.end());
reverse(s, 0, k - 1);
reverse(s, k, s.size() - 1);
cout << s << endl;
return 0;
}
28. 实现 strStr()
kmp第一次做,比较难,还没有理解,照着答案写了一遍。
class Solution {
public:
void getNext(int* next, const string& s) {
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++) {
while (j >= 0 && s[j + 1] != s[i]) {
j = next[j];
}
if (s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
vector<int> next(needle.size());
getNext(&next[0], needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while (j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
if (j == (needle.size() - 1)) {
return (i - needle.size() + 1);
}
}
return -1;
}
};
总结
字符串掌握得并不好。