Skip to content

Instantly share code, notes, and snippets.

@startupjing
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupjing/16b8e16d190c16ceb149 to your computer and use it in GitHub Desktop.
Save startupjing/16b8e16d190c16ceb149 to your computer and use it in GitHub Desktop.
my solutions--cc150 1.5
import java.util.*;
public class CompressStr {
/**
* ask user for input and output the compressed string
* @param args
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string (q to quit): ");
while(input.hasNextLine()){
String userStr = input.nextLine();
if(userStr.equals("q")){
System.out.println("quit...");
System.exit(0);
}
System.out.println("The compressed string is " + compress(userStr));
System.out.println();
System.out.println("Please enter another string (q to quit): ");
}
}
/**
* compress the string if needed
* @param s
* @return compressed string
*/
public static String compress(String s){
//tempCount to count number of char
int tempCount = 0;
//pointer to traverse the string
int i = 0;
StringBuffer result = new StringBuffer();
while(i < s.length()){
char tempChar = s.charAt(i);
while(s.charAt(i) == tempChar){
i++;
tempCount ++;
//if ptr exceeds the length, call for final result
if(i >= s.length()){
result.append("" + tempChar + tempCount);
return decideStr(result.toString(), s);
}
}
//append the character and its frequency
result.append("" + tempChar + tempCount);
tempCount = 0;
}
return decideStr(result.toString(), s);
}
/**
* return the string of shorter length
* @param s1
* @param s2
* @return string of shorter length
*/
public static String decideStr(String s1, String s2){
if(s1.length() < s2.length()){
return s1;
}else{
return s2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment