알고리즘/codefights

49>lineEncoding

Diademata 2017. 11. 4. 00:54
반응형

Given a string, return its encoding defined as follows:


First, the string is divided into the least possible number of disjoint substrings consisting of identical characters

for example, "aabbbc" is divided into ["aa", "bbb", "c"]

Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character

for example, substring "bbb" is replaced by "3b"

Finally, all the new strings are concatenated together in the same order and a new string is returned.

Example


For s = "aabbbc", the output should be

lineEncoding(s) = "2a3bc". 


code>>


std::string lineEncoding(std::string s) {

std::string r = "";

int count = 1;

for (int i = 1; i < s.length(); i++)

{

if (s[i] == s[i - 1])

count++;

else

{

if (count > 1)

{

r += std::to_string(count) + s[i - 1];

count = 1;

}

else

r += s[i - 1];

}

}

return  count > 1 ? r += std::to_string(count) + s[s.length() - 1] : r += s[s.length() - 1];

}

반응형