1:求子串:暴力穷举(Brute Force)
模式匹配:子串的定位运算称为串的模式匹配或串匹配。
假设有两个串S,T,设S为主串"asfheiufhre",T为子串"eiu".
在主串S中查找与模式T相匹配的子串,如果查找成功,返回匹配的子串第一个字符在主串中的位置。
//最笨的办法就是穷举所有S的所有子串,判断是否与r匹配。该算法称为BF(Brute Force)
int BF(string s,string t,int nPos)
{
int nSLen = s.length();
int nTLen = t.length();
if (0 == nSLen || 0 == nTLen || slen - nPos < nTLen)
{
return -1;
}
int i = nPos, j = 0;
while(i< nSLen && j< nTLen)
{
if(s[i]==t[j]) //如果相等,则继续比较后面的字符
{
i++;
j++;
}
else
{
i=i-j+1; //i回退到上一轮开始比较的下一个字符
j=0; //j回退到第0个字符
}
}
return (j == nTLen) ? (i - nTLen + 1) : -1; //j == nTLen匹配成功
}