1525. Number of Good Ways to Split a String

T: O(n)

S: O(n)

class Solution {
    public int numSplits(String s) {
        int n = s.length();
        int[] count = new int[26];
        int[] left = new int[n];
        int[] right = new int[n];
        
        int types = 0;
        for (int i = 0; i < n; i++) {
            count[s.charAt(i) - 'a']++;
            if (count[s.charAt(i) - 'a'] == 1) {
                types++;
            }
            left[i] = types;
        }
        
        count = new int[26];
        types = 0;
        for (int i = n-1; i >= 0; i--) {
            count[s.charAt(i) - 'a']++;
            if (count[s.charAt(i) - 'a'] == 1) {
                types++;
            }
            right[i] = types;
        }
        int res = 0;
        for (int i = 0; i < n-1; i++) {
            if (left[i] == right[i+1]) {
                res++;
            }
        }
        return res;
    }
}

/*
navie: O(n^L)
s = p + q

the number of distinct letters in p and q are the same.
    
ways of split to two string = s.len - 1
    
navie check two substring has (distinct letters), [substring], [substring]
    1 <= s.length <= 10^5



O(n) solution: 3 pass

                   i
|------left--------|---------right-----|

1.
pass from left first:
get kind of char in left[i]
use char[] to record when char[x] == 1, types++

2.
pass from right:
same 

3.
final 
loop i = 0 to < n-1 (at last, there is one char need to compare, so it's < n-1)
   if (left[i] == right[i+1])                 
        ways++
*/

another explain

Last updated

Was this helpful?