Day9
今天速刷三题,KMP还是挺难
151. Reverse Words in a String
其实不用这么麻烦,但我突发奇想了用这个思路继续往下写了。
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
// cout << s;
int idx = 0;
string ans = "";
string stack_str = "";
while(idx < s.length())
{
if(s[idx] == ' ' && stack_str != "")
{
reverse(stack_str.begin(), stack_str.end());
ans += stack_str;
ans += " ";
stack_str = "";
cout << ans << "\n";
while(s[idx] == ' ')
++idx;
}
else
{
if(s[idx] != ' ')
{
stack_str += s[idx];
}
++idx;
}
}
reverse(stack_str.begin(), stack_str.end());
ans += stack_str;
if(ans[ans.length()-1] == ' ')
return ans.substr(0, ans.length()-1);
return ans;
}
};
卡码网:55.右旋转字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
int k;
string str;
cin >> k >> str;
k = k % str.length();
string s1 = str.substr(str.length()-k, k);
string s2 = str.substr(0, str.length()-k);
cout << s1 + s2;
return 0;
}
28. Find the Index of the First Occurrence in a String
依旧难的KMP
class Solution {
public:
void getNext(int* next, string& s) {
int i=0;
next[0] = 0;
for(int j=1; j<s.length(); ++j) {
while(i>0 && s[i] != s[j]) {
i = next[i-1];
}
if(s[i] == s[j]){
++i;
}
next[j] = i;
}
}
int strStr(string haystack, string needle) {
if(needle.length() > haystack.length()) {
return -1;
}
vector<int> next(needle.length());
getNext(&next[0], needle);
int j=0;
for(int i=0; i<haystack.length(); ++i) {
while(j>0 && haystack[i] != needle[j]) {
j = next[j-1];
}
if(haystack[i] == needle[j]) {
++j;
}
if(j == needle.length()) {
return (i - needle.length() + 1);
}
}
return -1;
}
};