LeetCode 3167: Better Compression of String Solution
Master LeetCode problem 3167 (Better Compression of String), 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.
3167. Better Compression of String
Problem Explanation
Explanation:
The problem asks us to compress a given string by replacing consecutive repeating characters with the character followed by the count of consecutive repetitions. The compressed string should be as short as possible.
To solve this problem, we can iterate through the input string, keeping track of the current character and its count. We append the character and its count to a result string whenever we encounter a different character or reach the end of the input string. Solution:
Solution Code
class Solution {
public String compressString(String s) {
if (s == null || s.length() == 0) {
return s;
}
StringBuilder sb = new StringBuilder();
char prevChar = s.charAt(0);
int count = 1;
for (int i = 1; i < s.length(); i++) {
char currChar = s.charAt(i);
if (currChar == prevChar) {
count++;
} else {
sb.append(prevChar);
sb.append(count);
prevChar = currChar;
count = 1;
}
}
sb.append(prevChar);
sb.append(count);
return sb.length() < s.length() ? sb.toString() : s;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3167 (Better Compression of String)?
This page provides optimized solutions for LeetCode problem 3167 (Better Compression of String) 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 3167 (Better Compression of String)?
The time complexity for LeetCode 3167 (Better Compression of String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3167 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3167 in Java, C++, or Python.