LeetCode 75
String Compression
- Problem
- LC 443
- Topic
- Array / String
- File
- official75_LC443StringCompression.java
- Path
- pkg5leetcode/official75/official75_LC443StringCompression.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC443StringCompression.java
- Approach
- In-place write char then count digits.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * String Compression | LC 4435 * APPROACH: In-place write char then count digits.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC443StringCompression {9 static int compress(char[] chars) {10 int write = 0, read = 0;11 while (read < chars.length) {12 char c = chars[read];13 int count = 0;14 while (read < chars.length && chars[read] == c) { read++; count++; }15 chars[write++] = c;16 if (count > 1) {17 for (char d : String.valueOf(count).toCharArray()) chars[write++] = d;18 }19 }20 return write;21 }22 23 public static void main(String[] args) {24 char[] a = {'a','a','b','b','c','c','c'};25 check(compress(a) == 6 && a[0]=='a' && a[1]=='2' && a[2]=='b', "case1");26 char[] b = {'a'};27 check(compress(b) == 1 && b[0]=='a', "case2");28 System.out.println("all tests passed");29 }30 31 static void check(boolean cond, String name) {32 if (!cond) throw new AssertionError("FAILED: " + name);33 System.out.println(" PASS " + name);34 }35}