• Leetcode 1358 Number of Substrings Containing All Three Characters (滑动窗口)


    Leetcode 1358

    问题描述

    Given a string s consisting only of characters a, b and c.
    
    Return the number of substrings containing at least one occurrence of all these characters a, b and c.
    

    例子

    Example 1:
    Input: s = "abcabc"
    Output: 10
    Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). 
    
    Example 2:
    Input: s = "aaacb"
    Output: 3
    Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". 
    
    Example 3:
    Input: s = "abc"
    Output: 1
    

    方法一

    ** Solution Java **
    ** 6ms, beats 93.11% **
    ** 41.3MB, beats 100.00% **
    class Solution {
        public int numberOfSubstrings(String s) {
            int n = s.length(), res = 0, k = 3;
            char[] S = s.toCharArray();
            int[] count = new int[3];
            for (int i = 0, j = 0; j < n; ++j) {
                ++count[S[j] - 'a'];
                while(count[0] > 0 && count[1] > 0 && count[2] > 0)
                    --count[S[i++] - 'a'];
                res += i;
            }
            return res;
        }
    }
    

    方法二

    ** Solution Java **
    ** 4ms, 99.78% **
    ** 41.4MB, 100.00% **
    class Solution {
        public int numberOfSubstrings(String s) {
            int last[] = {-1, -1, -1}, res = 0, n = s.length();
            char[] S = s.toCharArray();
            for (int i = 0; i < n; ++i) {
                last[S[i] - 'a'] = i;
                res += 1 + Math.min(last[0], Math.min(last[1], last[2]));
            }
            return res;
        }
    }
    
  • 相关阅读:
    linux 下高精度时间
    pstack
    linux 调试常用命令
    定位 UNIX 上常见问题的经验总结
    在 POSIX 线程编程中避免内存泄漏
    ulimit
    设计模式之迭代器模式(PHP实现)
    设计模式之责任链模式(php实现)
    设计模式之代理模式(php实现)
    设计模式之享元模式(PHP实现)
  • 原文地址:https://www.cnblogs.com/willwuss/p/12525753.html
Copyright © 2020-2023  润新知