Created
August 22, 2015 09:34
-
-
Save reza-ryte-club/5dd7917d6b1a134500e2 to your computer and use it in GitHub Desktop.
Compress consecutive character occurrence of a character in a String
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
public class Compress { | |
public static String compressedString(String str){ | |
StringBuilder dest = new StringBuilder(); | |
for(int i=0;i<str.length();i++){ | |
char c = str.charAt(i); | |
dest.append(c); | |
int j = i; | |
int count =1 ; | |
if(i<str.length()-1) | |
if(j<str.length()-2){ | |
while(c==str.charAt(j+1)){ | |
count++; | |
j++; | |
i++; | |
}} | |
if(count>1) | |
dest.append(count); | |
} | |
return dest.toString(); | |
} | |
public static void main(String[] args) { | |
String word = "Hello"; | |
System.out.println(compressedString(word)); | |
//Output should be like hel2o | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment