1. 程式人生 > 其它 >242. 子串匹配

242. 子串匹配

思路:

只要列舉最終匹配的子串是從s中的哪個字元開始的就好了,並記錄最小值。

程式碼:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    // please define the C++ input here. For example: int a,b; cin>>a>>b;;
    // please finish the function body here.
    // please define the C++ output here. For example:cout<<____<<endl;
string str1; string str2; cin>>str1; cin>>str2; int t = 0; int count = 0; if(str1.find(str2)!=str1.npos) { cout<<0<<endl; return 0; } int max_len = str1.length()-str2.length() + 1; int ret = max_len; for(int i = 0;i<max_len;i++) {
if(str1[i] != str2[0]) { continue; } int temp = 0; int index_next = 1; for(int j = i+1;j<str1.length();j++) { if(str1[j]!=str2[index_next]) { temp++; }else{ index_next++; }
if(index_next==str2.length()) { if(ret >temp) { ret=temp; } } } } cout<<ret<<endl; return 0; }
以大多數人努力程度之低,根本輪不到去拼天賦~