686. Repeated String Match

方法一、算是暴力解法吧,拼一段找一下

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int repeatedStringMatch(string A, string B) 
12     {
13         string as=A;
14         int count=B.size()/A.size()+3;
15         for(int i=1;i<count;i++,as+=A)
16         {
17             if(as.find(B)!=string::npos)
18                 return i;
19         }
20         return -1;
21     }
22 };

方法二、稍微有点技术含量了,运行速度快些

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int repeatedStringMatch(string A, string B) 
12     {
13         string tmp=A+A;
14         size_t pos=tmp.find(B.substr(0,A.size()));
15         if(pos==string::npos)
16             return -1;
17         int count=1;
18         size_t i=0;
19         while(i<B.size())
20         {
21             if(pos==A.size())
22             {
23                 pos=0;
24                 ++count;
25             }
26             if(A[pos++]!=B[i++])
27                 return -1;
28         }
29         return count;
30     }
31 };

先把两个A拼起来成为tmp,在tmp中找B的前面一截,若没找到,则B必然不能成为A拼接序列的子串

若找到了,再进行下面的判定,一个字符一个字符来,扫到A末尾则回到A首部并增加计数器,直到找到B的所有元素

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9160275.html