LeetCode 3163: String Compression III Solution

Master LeetCode problem 3163 (String Compression III), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3163. String Compression III

Medium

Problem Explanation

Explanation:

  • We iterate over the input string word, keeping track of the current character and its count.
  • When we encounter a different character or reach the maximum count of 9 for the current character, we append the count and character to the result.
  • We continue this process until we reach the end of the string.

Time Complexity: O(n) where n is the length of the input string word Space Complexity: O(1)

Solution Code

class Solution {
    public String compress(String word) {
        StringBuilder sb = new StringBuilder();
        char prevChar = ' ';
        int count = 0;
        
        for (char c : word.toCharArray()) {
            if (c != prevChar || count == 9) {
                if (count > 0) {
                    sb.append(count);
                    sb.append(prevChar);
                }
                prevChar = c;
                count = 1;
            } else {
                count++;
            }
        }
        
        if (count > 0) {
            sb.append(count);
            sb.append(prevChar);
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3163 (String Compression III)?

This page provides optimized solutions for LeetCode problem 3163 (String Compression III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3163 (String Compression III)?

The time complexity for LeetCode 3163 (String Compression III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3163 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3163 in Java, C++, or Python.

Back to LeetCode Solutions