字符串移位包含问题

在编程之美3.1中,此题解法是用strstr()函数,并且以空间换时间,其实只要用循环遍历即可

其时间复杂度: k < O(n) < k + n, 其中k为查找串的长度,n为数据串的长度,空间复杂度为O(1)。

代码如下:

 1 #include
 2 using namespace std;
 3 
 4 int findSubStr(char source[], char subStr[], int sLen, int oLen)
 5 {
 6     if(source == NULL || subStr == NULL || sLen <=0 || oLen <=0)
 7     {
 8         return -1;
 9     }
10     int isShifting = 0;
11     for(int i = 0; i < sLen; i++)
12     {
13         if(subStr[0] == source[i])
14         {
15             isShifting = 1;
16             int s_index = i + 1;
17             for(int j = 1; j < oLen; j++)
18             {
19                 if(source[s_index] == subStr[j])
20                 {
21                     s_index++;
22                     if(s_index < sLen)
23                         continue;
24                     else
25                         s_index = 0;
26                 }
27                 else
28                 {
29                     isShifting = 1;
30                     i = s_index - 1;
31                     break;
32                 }
33             }
34         }
35     }
36     return isShifting;
37 }
38 
39 int main()
40 {
41     char source[] = "AABCDAACDB";
42     char subStr[] = "CDBA";
43     int sLen = strlen(source);
44     int oLen = strlen(subStr);
45     if(findSubStr(source,subStr, sLen, oLen) == 1)
46         cout << "True.." << endl;
47     else
48         cout << "False.." << endl;
49     return 0;
50 }

 

 

转载于:https://www.cnblogs.com/michaelGD/archive/2012/12/20/2827137.html

你可能感兴趣的:(字符串移位包含问题)