算法之字符串密码截取

分析和思路:把输入的字符串反转后,求最大的公共子串,同时判断是不是回文 1 #include "iostream"
2 #include "string" 3 #include "algorithm" 4 #include "vector" 5 using namespace std; 6 7 8 9 10 11 int main() 12 { 13 14 string str1; 15 string str2; 16 vector<string> b; 17 while(cin>>str1) 18 { 19 20 int max_len=0; 21 str2=str1; 22 reverse(str1.begin(),str1.end()); 23 //cout<<str1<<endl; 24 if(str1.size()==0||str2.size()==0) 25 { 26 cout<<0<<endl; 27 continue; 28 } 29 for(int i=0;i<str1.size();i++) 30 { 31 32 for(int j=0;j<str2.size();j++) 33 { 34 int count=0; 35 string temp; 36 if(str1[i]==str2[j]) 37 { 38 39 while(i<str1.size()&&j<str2.size()&&str1[i]==str2[j]) 40 { 41 temp.append(1,str1[i]); 42 count++; 43 i++; 44 j++; 45 } 46 47 if(count>=max_len) 48 { 49 int i=0; 50 int j=0; 51 if(temp[i]==temp[temp.size()-1-j]) 52 { 53 while(i<j) 54 { 55 if(temp[i]==temp[temp.size()-1-j]) 56 { 57 i++; 58 j--; 59 } 60 } 61 62 if(i!=j) 63 { 64
} 70 else 71 { 72 max_len=count; 77 b.clear(); 78 b.push_back(temp); 79 } 80 } 81 82 83 84 } 85 i=i-count;//重要,此处需要回退 86 j=j-count; 87 } 88 89 } 90 91 } 92 // cout<<b[0]<<endl; 93 cout<<max_len<<endl; 94 95 } 96 97 return 0; 98 }
主要为了自己学习

浙公网安备 33010602011771号