https://leetcode.com/problems/string-compression/
At first, I didn’t modified the input array by copying each element, but I just put an new array to the variable. Also I missed a condition that I have to count the chars separately if it is not consecutive.
class Solution {
public int compress(char[] chars) {
int n = chars.length;
if (n == 1) return 1;
StringBuilder sb = new StringBuilder();
List<Integer> cntList = new ArrayList<>();
for (char c : chars) {
int idx = sb.indexOf(String.valueOf(c));
//if the char is new
if (idx == -1) {
sb.append(c);
cntList.add(1);
} else {
int newVal = cntList.get(idx) + 1;
cntList.set(idx, newVal);
}
}//for
StringBuilder s = new StringBuilder();
for (int i = 0; i < cntList.size(); i++) {
s.append(sb.charAt(i));
if (cntList.get(i) != 1) s.append(cntList.get(i));
}
chars = s.toString().toCharArray();
return chars.length;
}
}
After I found out the problem, I passed with this code.
class Solution {
public int compress(char[] chars) {
int n = chars.length;
if (n == 1) return 1;
StringBuilder s = new StringBuilder();
int p1 = 0;
outer:
while (p1 < n) {
s.append(chars[p1]);
//if the pointer is at the end of the array, just finish the loop
if (p1 >= n - 1) break;
int cnt = 1;
int p2 = p1 + 1;
while (true) {
//if they are consecutive repeating chars and p2 is not at the end
if (chars[p1] == chars[p2] && p2 < n - 1) {
p2++;
cnt++;
} else if (chars[p1] == chars[p2] && p2 >= n - 1) {
cnt++;
if (cnt != 1) s.append(cnt);
break outer;
}
//if not
else {
if (cnt != 1) s.append(cnt);
p1 = p2;
break;
}
}//while for p2
}// while for p1
for (int i = 0; i < s.length(); i++) {
chars[i] = s.charAt(i);
}
return s.length();
}
}
I had to use two loops because I didn’t know how to get right index of the new array in the while loop. Because of this, my time complexity was bigger than others. So I studied the better code.
class Solution {
public int compress(char[] chars) {
int pointer = 0;
int idx = 0;
while (idx < chars.length) {
int charLength = 1;
while (chars[pointer] == chars[pointer + charLength] && pointer + charLength < chars.length) {
charLength++;
}
chars[idx++] = chars[pointer];
if (charLength > 1) {
for (char c : String.valueOf(charLength).toCharArray()) {
chars[idx++] = c;
}
}
pointer += charLength;
}//while
return idx;
}
}
This code has a variable for the index and increase the number only if the char is updated in the array.