題目地址
https://leetcode-cn.com/problems/maximum-repeating-substring/
題目描述
給你一個字符串 sequence ,如果字符串 word 連續(xù)重復(fù) k 次形成的字符串是 sequence 的一個子字符串,那么單詞 word 的 重復(fù)值為 k 。單詞 word 的 最大重復(fù)值 是單詞 word 在 sequence 中最大的重復(fù)值。如果 word 不是 sequence 的子串,那么重復(fù)值 k 為 0 。
給你一個字符串 sequence 和 word ,請你返回 最大重復(fù)值 k 。
示例 1:
輸入:sequence = "ababc", word = "ab"
輸出:2
解釋:"abab" 是 "ababc" 的子字符串。
示例 2:
輸入:sequence = "ababc", word = "ba"
輸出:1
解釋:"ba" 是 "ababc" 的子字符串,但 "baba" 不是 "ababc" 的子字符串。
示例 3:
輸入:sequence = "ababc", word = "ac"
輸出:0
解釋:"ac" 不是 "ababc" 的子字符串。
提示:
1 <= sequence.length <= 100
1 <= word.length <= 100
sequence 和 word 都只包含小寫英文字母。
思路
- 暴力法,遍歷數(shù)組,找字串最大值。
- 利用Java String的contains函數(shù),如果存在字串,就多拼接上一個word,再次看是否有這個字串,如果有,再拼一個word,這樣就能找到最大子串。
題解
class Solution {
/**
* 執(zhí)行用時:1 ms, 在所有 Java 提交中擊敗了93.63%的用戶
* 內(nèi)存消耗:36.7 MB, 在所有 Java 提交中擊敗了68.25%的用戶
*/
public int maxRepeatingV2(String sequence, String word) {
int count=0;
String tmp=word;
while(sequence.contains(word)){
word+=tmp;
count++;
}
return count;
}
/**
* 執(zhí)行用時:1 ms, 在所有 Java 提交中擊敗了93.63%的用戶
* 內(nèi)存消耗:36.6 MB, 在所有 Java 提交中擊敗了84.65%的用戶
*/
public int maxRepeating(String sequence, String word) {
if (sequence.length() == 1 && (sequence.equals(word))) {
return 1;
}
int len = word.length();
int max = 0;
char first = word.charAt(0);
for (int i=0; i<sequence.length(); i++) {
char current = sequence.charAt(i);
if (current != first) {
continue;
}
int rep = 0;
for (int j=i,k=0; j<sequence.length(); j++,k++) {
int pos = k % len;
if (sequence.charAt(j) == word.charAt(pos)) {
if (pos == len - 1) {
rep++;
}
} else {
break;
}
}
max = Math.max(max, rep);
}
return max;
}
}