三、包含所有三种字符的子字符串数目(Biweekly20)

题目描述:
给你一个字符串 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;
    
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章