题解 | #分品种#
分品种
https://www.nowcoder.com/practice/9af4e93b04484df79d4cc7a863343b0b
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型一维数组 */ public int[] partitionLabels (String s) { // write code here HashMap<Character, Integer> map = new HashMap<Character, Integer>(); HashSet<Character> set = new HashSet<>(); for (int i = 0; i < s.length(); i++) { if (map.containsKey(s.charAt(i))) { map.put(s.charAt(i), map.get(s.charAt(i)) + 1); } else { map.put(s.charAt(i), 1); } } ArrayList<Integer> arr = new ArrayList<Integer>(); int len = 0; set.add(s.charAt(0)); map.put(s.charAt(0), map.get(s.charAt(0)) - 1); for (int i = 1; i < s.length(); i++) { if (isTrue(set, map)) { arr.add(i); set.clear(); } char cur = s.charAt(i); set.add(cur); map.put(cur, map.get(cur) - 1); } if (arr.size() == 0) { return new int[]{s.length()}; } int[] res = new int[arr.size() + 1]; res[0] = arr.get(0); res[res.length - 1] = s.length() - arr.get(arr.size() - 1); for (int i = arr.size() - 1; i > 0; i--) { res[i] = arr.get(i) - arr.get(i - 1); } return res; } public boolean isTrue(HashSet<Character> set, HashMap<Character, Integer> map) { for (Character c : set) { if (map.get(c) != 0) { return false; } } return true; } }