给多个字符串,找最长前缀
暴力匹配,先按字典序排序字符串,这样长度短的优先进行匹配,所得字符串就可能偏小
适合a aa aaa aaaa
这样的数据,不过对于aa aab aabc aabcd
没用
#include
using namespace std;
string solve(const string &s1,const string &s2)
{
string ans;
int lg=min(s1.size(),s2.size());
for(int i=0;i& strs)
{
sort(strs.begin(),strs.end());
int lg=strs.size();
if(lg==1) return strs[0];
string ans=solve(strs[0],strs[1]);
for(int i=2;istrs;string str;
while(cin>>str)
{
strs.push_back(str);
}
string ans=longestCommonPrefix(strs);
cout<
如题
枚举每个子串的中间段,需要特别注意中间段的长度可以为奇数也可以为偶数
所以处理的时候,先把和给定中心点相邻的相同字符都归入中间段
#include
using namespace std;
string longestPalindrome(string s)
{
string ret;
int ans=0,lg=s.size();
for(int i=0;i=0&&s[l-1]==s[r]) l--;
while(r+1=0 &&s[r+1]==s[l-1])
{
l--;
r++;
}
if(r-l+1>ans)
{
ans=r-l+1;
ret=s.substr(l,r-l+1);
}
}
return ret;
}
int main()
{
string s;cin>>s;
string ans=longestPalindrome(s);
cout<
将单词顺序翻转,单词保持原样
先整体翻转,然后轮流执行单词翻转和多个空格替换成一个空格
#include
using namespace std;
string reverseWords(string s)
{
int l=0,lg=s.size(),r=lg-1;
while(s[l]==' ')l++;
while(s[r]==' ')r--;
s=s.substr(l,r-l+1);lg=s.size();
reverse(s.begin(),s.end());
bool zt=1;l=0,r=0;
while(l
实现字符串匹配KMP算法
KMP板子,next数组里存的是最长相同前后缀,next[length]
表示[0,length-1](不包含length)的最长相同前后缀,前后缀不能包含整个子串,就如[0,length-1]的前缀最多取到[0,length-2],所以构建next的时候,mao=1,had=0
#include
using namespace std;
void getNext(vector&next,const string& needle)
{
const int lg=needle.size();
next.resize(lg+1);
int mao=1,had=0;
for(;mao next;
getNext(next,needle);
cout<<"getNext Done"<>haystack>>needle;
int ans=strStr(haystack,needle);
}