459. Repeated Substring Pattern
1.問題描述
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: “abab”
Output: True
Explanation: It’s the substring “ab” twice.
Example 2:
Input: “aba”
Output: False
Example 3:
Input: “abcabcabcabc”
Output: True
Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)
來自 https://leetcode.com/problems/repeated-substring-pattern/description/
2.題目分析
給定一個非空字符串,檢測這個字符串是否可以由它的一個子串通過拼接構造出來,即判斷字符串的周期性。通過find函數找出第一個和和s[0]相同的位置,假設這個位置gap是周期,再通過isminsubstr函數判斷字符串是否是這個周期的,若函數返回true,則結束,返回true,否者再通過find尋找下一個可能的周期。其中isminsubstr函數用于判斷字符串是否具有周期gap,判斷的方法是首先這個字符串長度必須是gap的整數倍,其次,各個位置的字符必須周期重復。
3.C++代碼
//我的代碼:(beats 39%) bool isminsubstr(string s, int gap)//判斷s是否具有周期gap {int L = s.length();if(L%gap != 0)//長度不是gap的整數倍return false;for(int start=0;start<gap;start++)for (int i = start+gap; i < L; i=i+gap){if (s[start] != s[i])//不滿足周期重復return false;}return true; } bool repeatedSubstringPattern(string s) {int L = s.length();int gap = s.find(s[0],1);//假設的最小周期if (gap == -1)return false;while (gap < L&&gap!=-1){if (isminsubstr(s, gap))return true;elsegap= s.find(s[0], gap+1);//尋找下一個周期}return false; } //別人家的代碼 bool repeatedSubstringPattern2(string str) {int i = 1, j = 0, n = str.size();vector<int> dp(n+1,0);while (i < str.size()){if (str[i] == str[j])dp[++i] = ++j;else if (j == 0)++i;elsej = dp[j];}return dp[n] && ((dp[n] % (n - dp[n])) == 0); } //基本思路4.string類的compare函數
在C++中使用std::string編寫字符串相關操作時,經常使用find方法,但在有些場景下需要判斷字符串是否相同,因而需要使用compare方法。下面是用法測試:
#include <string> #include <iostream> using namespace std; int main(int argc, char* argv[]) {string str1("abc");string str2("abcabcabc");if (str1.compare("abc") == 0)cout << str1 << " is abc!" << endl;if (str1.compare(str2) != 0)cout << str1 << " is not " << str2 << endl;if (str2.compare(6, 3, "abc") == 0)cout << str2 << " 'index from 6 about 3char is abc!" << endl;if (str2.compare(0,3, str1) == 0)cout << str2 << " 'index from 0 about 3char is equal str1!" << endl;if (str2.compare(6, 3, str1, 0, 3) == 0)cout << str2 << " 'index from 6 about 3char is equal str1'index from 0 about 3char!" << endl;return 0; }總結
以上是生活随笔為你收集整理的459. Repeated Substring Pattern的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PaddleHub创意项目-制作证件照(
- 下一篇: 酷狗音乐(繁星网)PHP岗位笔试题