LeetCode刷題實(shí)戰(zhàn)467:環(huán)繞字符串中唯一的子字符串
We define the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Given a string p, return the number of unique non-empty substrings of p are present in s.
示例? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
示例?1:
輸入:?"a"
輸出:?1
解釋: 字符串 S 中只有一個(gè)"a"子字符。
?
示例?2:
輸入:?"cac"
輸出:?2
解釋: 字符串 S 中的字符串“cac”只有兩個(gè)子串“a”、“c”。.
?
示例?3:
輸入:?"zab"
輸出:?6
解釋: 在字符串 S 中有六個(gè)子串“z”、“a”、“b”、“za”、“ab”、“zab”。.
解題
public?int?findSubstringInWraproundString(String p)?{
????????int?len = p.length();
????????int[] tabLen =?new?int[26];// 記錄以26個(gè)字母結(jié)尾的有效字符串個(gè)數(shù)(去重之后的)
????????int?curLen =?1;// 當(dāng)前連續(xù)字符串(有效)長(zhǎng)度,自己?jiǎn)为?dú)出現(xiàn),默認(rèn)初始值是1
????????tabLen[p.charAt(0) -?'a'] =?1;
?????????for?(int?i =?1; i < p.length(); ++i) {
????????????int?pre = p.charAt(i -?1) -?'a';
????????????int?cur = p.charAt(i) -?'a';
????????????if?((cur - pre +?26) %?26?==?1)
???????????????curLen++;
????????????else?
???????????????curLen =?1;
????????????// 為什么下面是取max?
????????????//比如zaba, 最后一個(gè)a單獨(dú)出現(xiàn)的情況已經(jīng)在第一個(gè)a出現(xiàn)的時(shí)候計(jì)算過(guò)了
?????????????// 最后一個(gè)a造成的答案長(zhǎng)是1,但是第一個(gè)a可以造成a,za兩個(gè)結(jié)果
?????????????// 所以,對(duì)于a這個(gè)字符,取最大的也就是第一個(gè)a產(chǎn)生的子集
????????????tabLen[cur] = Math.max(tabLen[cur], curLen);
?????????}
??????????
????????int?ans =?0;
????????//累加數(shù)組的值得到所有字母結(jié)尾有效字符串的和
????????for?(int?count : tabLen) ans += count;
????????return?ans;
??}
LeetCode1-460題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)461:漢明距離
LeetCode刷題實(shí)戰(zhàn)462:最少移動(dòng)次數(shù)使數(shù)組元素相等 II
LeetCode刷題實(shí)戰(zhàn)463:島嶼的周長(zhǎng)
LeetCode刷題實(shí)戰(zhàn)464:我能贏嗎
LeetCode刷題實(shí)戰(zhàn)465:最優(yōu)賬單平衡
LeetCode刷題實(shí)戰(zhàn)466:統(tǒng)計(jì)重復(fù)個(gè)數(shù)
