151.翻转字符串里的单词
思路:先去空格,翻转整个字符串,然后翻转每个单词。
题解:
class Solution {
public:
void reverse(string &s, int left, int right)
{
while (left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
}
string reverseWords(string s) {
int slow = 0;
for (int i = 0; i < s.size(); ++i)
{
if (s[i] != ' ')
{
if (slow != 0) s[slow++] = ' ';
while(s[i] != ' ' && i < s.size()) s[slow++] = s[i++];
}
}
s.resize(slow);
reverse(s, 0, s.size() - 1);
int start = 0;
for (int i = 0; i <= s.size(); i++)
{
if (i == s.size() || s[i] == ' ')
{
reverse(s, start, i-1);
start = i + 1;
}
}
return s;
}
};
卡码网:55.右旋转字符串
题目链接:右旋转字符串
思路:先翻转整个字符串,然后分别翻转两段字符。
题解:
# include<iostream>
# include<string>
using namespace std;
void reverse(string &s, int left, int right)
{
while(left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
}
int main(){
int k;
string s;
cin >> k;
cin >> s;
reverse(s, 0, s.size()-1);
reverse(s, 0, k-1);
reverse(s, k, s.size()-1);
cout << s;
}
28. 实现 strStr()
思路:考察KMP,需要知道如何生成前缀表。
题解:
class Solution {
public:
void getNext(const string &s, int *next)
{
int j = 0;
next[0] = j;
for (int i = 1; i < s.size(); ++i)
{
while(j > 0 && s[j] != s[i]) j = next[j-1];
if (s[j] == s[i]) ++j;
next[i] = j;
}
}
int strStr(string haystack, string needle) {
vector<int> next(needle.size());
getNext(needle, &next[0]);
int j = 0;
for (int i = 0; i < haystack.size(); ++i)
{
while(j > 0 && haystack[i] != needle[j]) j = next[j-1];
if (haystack[i] == needle[j]) ++j;
if (j == needle.size()) return i + 1 - needle.size();
}
return -1;
}
};
459.重复的子字符串
思路:同上
题解:
class Solution {
public:
void getNext(const string &s, int *next)
{
int j = 0;
next[0] = j;
for (int i = 1; i < s.size(); ++i)
{
while(j > 0 && s[j] != s[i]) j = next[j-1];
if (s[j] == s[i]) ++j;
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
vector<int> next(s.size());
getNext(s, &next[0]);
if (next[s.size() - 1] != 0)
{
int sublen = s.size() - next[s.size() - 1];
if (s.size() % sublen == 0)
return true;
}
return false;
}
};