Problem Statement
Given a string s, compress it using run-length encoding such that consecutive repeating characters are replaced with the character followed by the count of its occurrences.
Input:
s = "aaabbbccc"
Output: "a3b3c3"
Input: s = "abcd"
Output: "a1b1c1d1"
Input: s = "aabcccccaaa"
Output: "a2b1c5a3"
Input: s = "z"
Output: "z1"Constraints
1 <= s.length <= 10^5
s consists only of lowercase English letters.
public:
string encodeString(string s) {
string result;
int n = s.size();
for (int i = 0; i < n; ) {
char c = s[i];
int count = 0;
while (i < n && s[i] == c) {
count++;
i++;
}
result += c;
result += to_string(count);
}
return result;
}
};Complexity
Time: O(n)
Space: O(n) for the output string
#Hashmap #string #problem #leetcode #interview