Seawolf 发表于 2019-9-8 06:16:53

leetcode 1180. Count Substrings with Only One Distinct Letter

Given a string S, return the number of substrings that have only one distinct letter.



Example 1:

Input: S = "aaaba"
Output: 8
Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
"aaa" occurs 1 time.
"aa" occurs 2 times.
"a" occurs 4 times.
"b" occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.
Example 2:

Input: S = "aaaaaaaaaa"
Output: 55


Constraints:

1 <= S.length <= 1000
S consists of only lowercase English letters.

class Solution {
    public int countLetters(String S) {
      if (S.length() == 0) return 0;
      if (S.length() == 1) return 1;
      int sum = 0;
      String remain = "";
      Set <String> set = new HashSet<>();
      String init = S.substring(0,1);
      set.add(init);
      for(int i = 0; i< S.length(); i++){
            
            if(S.substring(i,i+1).equals(init)) {
               
                remain = remain + S.substring(i,i+1);
                set.add(remain + S.substring(i,i+1));
            }
            else {
                remain = "";
                init = S.substring(i,i+1);
               
                set.add(init);
            }
      }
      Iterator<String> iterator = set.iterator();
      while(iterator.hasNext()) {
            sum = sum + compare(S,iterator.next());
      }
      
      return sum;
    }
   
    public int compare(String S, String s){
      int sum = 0;
      for(int i = 0; i<= S.length() - s.length(); i++){
            if(S.substring(i,i+s.length()).equals(s)) sum ++;
            
      }
      return sum;
    }
}
页: [1]
查看完整版本: leetcode 1180. Count Substrings with Only One Distinct Letter