1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution { public int compress(char[] chars) { int n = chars.length; int[] parent = new int[n]; for(int i = 0; i < n; i++){ parent[i] = i; } for(int i = 1; i < n; i++){ char ch = chars[i]; if(ch == chars[i-1]){ union(i, i-1, parent); } }
StringBuffer sb = new StringBuffer(); int count = 1; sb.append(chars[0]); for(int i = 1; i < n; i++){ int pre = find(i-1, parent); int p1 = find(i, parent); if(pre == p1){ count++; }else{ if(count != 1){ sb.append(count +""); count = 1; } sb.append(chars[i] +""); } }
if(count != 1){ sb.append(count +""); count = 0; }
for(int i = 0; i < sb.length(); i++){ chars[i] = sb.charAt(i); } return sb.length(); }
public int find(int k, int[] parent){ if(k != parent[k]){ parent[k] = find(parent[k], parent); } return parent[k]; }
public void union(int i, int j, int[] parent){ int x = find(i, parent); int y = find(j, parent); if(x != y){ parent[x] = y; } } }
|