Created
June 9, 2018 17:09
-
-
Save neerajkumar/32f8fbda11148115e4ae2437ed862dbd to your computer and use it in GitHub Desktop.
Compressing a string, but without corner cases. - Ruby Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Compressing a string, but without corner cases. | |
## e.g. aaaaaaaabbbbbbb ==> a8b7 | |
## abcdef => abcdef | |
def compress_string(str) | |
count = 1 | |
can_be_compressed = false | |
compressed_string = '' | |
i = 1 | |
while(i <= str.length) do | |
if str[i - 1] == str[i] | |
count += 1 | |
can_be_compressed = true if count > 1 | |
else | |
compressed_string += str[i - 1] | |
compressed_string += count.to_s unless count == 1 | |
count = 1 | |
end | |
i += 1 | |
end | |
if can_be_compressed | |
return compressed_string | |
else | |
return str | |
end | |
end | |
puts compress_string('abcaaabbb') | |
puts compress_string('abcdefgh') | |
puts compress_string('aaaaaaaabbbbbbb') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment