151
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(),s.end());
int n = s.size();
int pos = 0;
for(int start = 0;start < n;++start)
{
if(s[start] != ' ')
{
if(pos != 0) s[pos++] = ' ';
int end = start;//慢指向快
while(end < n && s[end] != ' ') s[pos++] = s[end++];
reverse(s.begin() + pos - (end - start),s.begin() + pos);
start = end;
}
}
s.erase(s.begin() + pos,s.end());
return s;
}
};
55字符串尾部的若干个字符转移到字符串的前面
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
string s;
cin >> n;
cin >> s;
int len = s.size();
//获取长度
reverse(s.begin(), s.begin() + len - n);
// 先反转前一段,长度len-n ,注意这里是和版本一的区别
reverse(s.begin() + len - n, s.end());
// 再反转后一段
reverse(s.begin(), s.end());
// 整体反转
cout << s << endl;
}
28最长相等前后缀不包含的这个子串就是最小重复的子串、iii没有回退
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(),m = needle.size();
if(m == 0) return 0;
vector<int> pi(m);
for(int i = 1,j = 0;i < m;i++)
{
while(j > 0 && needle[i] != needle[j])
{
j = pi[j - 1];
}
if(needle[i] == needle[j])
{
j++;
}
pi[i] = j;
}
for(int i = 0,j = 0;i < n;i++)
{
while(j > 0 && haystack[i] != needle[j])
{
j = pi[j - 1];
}
if(haystack[i] == needle[j])
{
j++;
}
if(j == m){return i - m + 1;}//???
}
return -1;
}
};
459待补全