題目描述:
給你一個字符串 s ,它只包含三種字符 a, b 和 c 。
請你返回 a,b 和 c 都 至少 出現過一次的子字符串數目。
示例 1:
輸入:s = “abcabc”
輸出:10
解釋:包含 a,b 和 c 各至少一次的子字符串爲 “abc”, “abca”, “abcab”, “abcabc”, “bca”, “bcab”, “bcabc”, “cab”, “cabc” 和 “abc” (相同字符串算多次)。
示例 2:
輸入:s = “aaacb”
輸出:3
解釋:包含 a,b 和 c 各至少一次的子字符串爲 “aaacb”, “aacb” 和 “acb” 。
示例 3:
輸入:s = “abc”
輸出:1
提示:
3 <= s.length <= 5 x 10^4
s 只包含字符 a,b 和 c 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/number-of-substrings-containing-all-three-characters
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
這裏爲了防止超時,我建立一個臨時的tem數組,tem[i][0]表示的是從下標i開始最早出現a的下標,tem[i][1]表示的是從下標i開始最早出現b的下標,tem[i][2]表示的是從下標i開始最早出現c的下標
代碼如下:
class Solution {
public int numberOfSubstrings(String s) {
Set<Character> set = new HashSet<> ();
int res = 0;
// 表示以i打頭的能組成多少個
// 記錄最近一次出現完整的路徑的下標 0 -> a 1 -> b 2 ->c
int [][] tem = new int[s.length ()][3];
Map<Character,Integer> map = new HashMap<> ();
for (int i = s.length () - 1; i >= 0; i--) {
map.put (s.charAt (i),i);
for (int j = 0; j < 3; j++) {
tem[i][j] = map.getOrDefault ((char)('a' + j),Integer.MAX_VALUE);
}
}
for (int i = 0; i < tem.length; i++) {
int[] ints = tem[i];
}
for (int i = 0; i < s.length (); i++) {
int max = Math.max (Math.max (tem[i][0],tem[i][1]),tem[i][2]);
if(max == Integer.MAX_VALUE){
continue;
}
res += s.length () - max;
}
return res;
}
}