151.翻转字符串里的单词
思路:用快慢双指针重置空格,先整体翻转再局部翻转
代码:
class Solution {
public:
void removeSpace(string &s){
int slow=0;
for(int fast=0;fast<s.size();fast++){
if(slow!=0&&s[fast]!=' ')
s[slow++]=' ';
while(fast<s.size()&&s[fast]!=' '){
s[slow++]=s[fast++];
}
}
s.resize(slow);
}
string reverseWords(string s) {
removeSpace(s);
reverse(s.begin(),s.end());
int slow=0;
for(int i=0;i<s.size();i++){
if(s[i]==' '){
reverse(s.begin()+slow,s.begin()+i);
slow=i+1;
}
if(i==s.size()-1){
reverse(s.begin()+slow,s.end());
}
}
return s;
}
};
卡码网:55.右旋转字符串
题目:55. 右旋字符串(第八期模拟笔试) (kamacoder.com)
思路:和上题相同,先整体翻转再局部翻转
代码:
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
string s;
cin>>n;
cin>>s;
reverse(s.begin(),s.end());
reverse(s.begin(),s.begin()+n);
reverse(s.begin()+n,s.end());
cout<<s<<endl;
return 0;
}
28. 实现 strStr()
思路:看猫片算法的经典应用。
代码:
class Solution {
public:
void getNext(int* next,const string& s){
int j=0;
next[0]=0;
for(int i=1;i<s.size();++i){
while(j>0&&s[i]!=s[j]){
j=next[j-1];
}
if(s[i]==s[j]){
j++;
}
next[i]=j;
}
}
int strStr(string haystack, string needle) {
int next[needle.size()];
getNext(next,needle);
int j=0;
int i=0;
for(i=0;i<haystack.size();++i){
while(j>0&&needle[j]!=haystack[i])
j=next[j-1];
if(needle[j]==haystack[i])
j++;
if(j==needle.size())
break;
}
if(i!=haystack.size()){
return i-needle.size()+1;
}
else
return-1;
}
};
459.重复的子字符串
思路:看猫片,利用next数组的公共前后缀相等。
代码:
class Solution {
public:
void getNext(int* next,const string& s){
int j=0;
next[0]=0;
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) {
if(s.size()==0)
return false;
int next[s.size()];
getNext(next,s);
if(next[s.size()-1]!=0&&s.size()%(s.size()-next[s.size()-1])==0)
return true;
else
return false;
}
};
标签:第九天,string,int,needle,随想录,next,字符串,size
From: https://blog.csdn.net/dtgfhfd/article/details/140362414