the third one in Biweekly Contest 31.
Difficulty : Medium
Related Topics : String、Bit Manipulation
You are given a string
s
, a split is called good if you can splits
into 2 non-empty stringsp
andq
where its concatenation is equal tos
and the number of distinct letters inp
andq
are the same.Return the number of good splits you can make in
s
.Input: s = "aacaba" Output: 2 Explanation: There are 5 ways to split "aacaba" and 2 of them are good. ("a", "acaba") Left string and right string contains 1 and 3 different letters respectively. ("aa", "caba") Left string and right string contains 1 and 3 different letters respectively. ("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.
Input: s = "abcd" Output: 1 Explanation: Split the string as follows ("ab", "cd").
Input: s = "aaaaa" Output: 4 Explanation: All possible splits are good.
Input: s = "acbadbaada" Output: 2
s
contains only lowercase English letters.1 <= s.length <= 10^5
- mine
- Java
Runtime: 23 ms, faster than 51.50%, Memory Usage: 40.8 MB, less than 52.46% of Java online submissions
// O(N)time // O(D)space D is the count of distinct char in s public int numSplits(String s) { char[] arr = s.toCharArray(); Map<Character, Integer> map = new HashMap<>(); Set<Character> set = new HashSet<>(); for (char c : arr) { map.put(c, map.getOrDefault(c, 0) + 1); } int res = 0; for (int i = 0; i < arr.length; i++) { char c = arr[i]; set.add(c); int t = map.getOrDefault(c, 0); if (t > 1) { map.put(c, t - 1); } else { map.remove(c); } if (set.size() == map.size()) { res++; } } return res; }
- Java
- the most votes
- Sliding Window
Runtime: 5 ms, faster than 94.30%, Memory Usage: 39.4 MB, less than 94.54% of Java online submissions
// O(N)time // O(1)space public int numSplits(String str) { int[] l = new int[26]; int[] r = new int[26]; int d_l = 0, d_r = 0; int res = 0; char[] s = str.toCharArray(); for (char ch : s) { d_r += ++r[ch - 'a'] == 1 ? 1 : 0; } for (int i = 0; i < s.length; ++i) { d_l += ++l[s[i] - 'a'] == 1 ? 1 : 0; d_r -= --r[s[i] - 'a'] == 0 ? 1 : 0; res += d_l == d_r ? 1 : 0; } return res; }