Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
Example:
Input: str = "AAAABBBCCDAA"
Output: 4A3B2C1D2A
Approach
C++
#include <bits/stdc++.h>using namespace std;int main(){string str = "AAAABBBCCDAA";char t = str[0];int i = 0;int cnt = 1;int n = str.size();string res = "";while (i < n){cnt = 1;i++;while (i < n && str[i] == str[i - 1]){i++;cnt++;}res += to_string(cnt);res += str[i-1];}cout << res << "\n";return 0;}
No comments:
Post a Comment