問題:數組
Consider the string s
to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s
will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".ide
Now we have another string p
. Your job is to find out how many unique non-empty substrings of p
are present in s
. In particular, your input is the string p
and you need to output the number of different non-empty substrings of p
in the string s
.this
Note: p
consists of only lowercase English letters and the size of p might be over 10000.spa
Example 1:code
Input: "a" Output: 1 Explanation: Only the substring "a" of string "a" is in the string s.
Example 2:字符串
Input: "cac" Output: 2 Explanation: There are two substrings "a", "c" of string "cac" in the string s.
Example 3:input
Input: "zab" Output: 6 Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.
解決:string
【題意】it
字符串s是小寫字母"abcdefghijklmnopqrstuvwxyz"的無限循環,s看起來像這樣:"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."io
如今咱們有另一個字符串p。你須要尋找p有多少個非空子串在s中出現。輸入p,你須要輸出s中有多少個不一樣的p的非空子串。
① 因爲封裝字符串是26個字符按順序無限循環組成的,那麼知足題意的p的子字符串要麼是單一的字符,要麼是按字母順序的子字符串。
咱們看abcd這個字符串,以d結尾的子字符串有abcd, bcd, cd, d,那麼咱們能夠發現bcd或者cd這些以d結尾的字符串的子字符串都包含在abcd中,那麼咱們知道以某個字符結束的最大字符串包含其餘以該字符結束的字符串的全部子字符串。那麼題目就能夠轉換爲分別求出以每一個字符(a-z)爲結束字符的最長連續字符串就好了,咱們用一個數組count記錄下來,最後在求出數組count的全部數字之和就是咱們要的結果了。
class Solution { //18ms
public int findSubstringInWraproundString(String p) {
if (p == null || p.length() == 0) return 0;
int[] count = new int[26];//記錄以每一個字符爲結尾的字符串的長度
int len = 0;//記錄子串的長度
char[] pchar = p.toCharArray();
for (int i = 0;i < pchar.length;i ++){
if (i > 0 && (pchar[i] == pchar[i - 1] + 1 || pchar[i - 1] - pchar[i] == 25)){
len ++;
}else {
len = 1;
}
count[pchar[i] - 'a'] = Math.max(count[pchar[i] - 'a'],len);
}
int res = 0;
for (int i = 0;i < count.length;i ++){
res += count[i];
}
return res;
}
}
② 進化版
class Solution { //17ms public int findSubstringInWraproundString(String p) { if (p == null || p.length() == 0){ return 0; } int[] count = new int[26]; int res = 0; int len = 0; char[] pchar = p.toCharArray(); for (int i = 0;i < pchar.length;i ++){ int cur = pchar[i] - 'a'; if (i > 0 && pchar[i - 1] != (cur + 26 - 1) % 26 + 'a'){ len = 0; } if (++ len > count[cur]){ res += len - count[cur]; count[cur] = len; } } return res; } }