459. Repeated Substring Pattern
1.問(wèn)題描述
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.)
來(lái)自 https://leetcode.com/problems/repeated-substring-pattern/description/
2.題目分析
給定一個(gè)非空字符串,檢測(cè)這個(gè)字符串是否可以由它的一個(gè)子串通過(guò)拼接構(gòu)造出來(lái),即判斷字符串的周期性。通過(guò)find函數(shù)找出第一個(gè)和和s[0]相同的位置,假設(shè)這個(gè)位置gap是周期,再通過(guò)isminsubstr函數(shù)判斷字符串是否是這個(gè)周期的,若函數(shù)返回true,則結(jié)束,返回true,否者再通過(guò)find尋找下一個(gè)可能的周期。其中isminsubstr函數(shù)用于判斷字符串是否具有周期gap,判斷的方法是首先這個(gè)字符串長(zhǎng)度必須是gap的整數(shù)倍,其次,各個(gè)位置的字符必須周期重復(fù)。
3.C++代碼
//我的代碼:(beats 39%) bool isminsubstr(string s, int gap)//判斷s是否具有周期gap {int L = s.length();if(L%gap != 0)//長(zhǎng)度不是gap的整數(shù)倍return false;for(int start=0;start<gap;start++)for (int i = start+gap; i < L; i=i+gap){if (s[start] != s[i])//不滿足周期重復(fù)return false;}return true; } bool repeatedSubstringPattern(string s) {int L = s.length();int gap = s.find(s[0],1);//假設(shè)的最小周期if (gap == -1)return false;while (gap < L&&gap!=-1){if (isminsubstr(s, gap))return true;elsegap= s.find(s[0], gap+1);//尋找下一個(gè)周期}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函數(shù)
在C++中使用std::string編寫(xiě)字符串相關(guān)操作時(shí),經(jīng)常使用find方法,但在有些場(chǎng)景下需要判斷字符串是否相同,因而需要使用compare方法。下面是用法測(cè)試:
#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; }總結(jié)
以上是生活随笔為你收集整理的459. Repeated Substring Pattern的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PaddleHub创意项目-制作证件照(
- 下一篇: 分享网站变黑白色代码整站灰色插件方法