Skip to content

Instantly share code, notes, and snippets.

@astkaasa
Created April 17, 2013 18:08
Show Gist options
  • Save astkaasa/5406441 to your computer and use it in GitHub Desktop.
Save astkaasa/5406441 to your computer and use it in GitHub Desktop.
problem 1.5
import java.util.Scanner;
public class StringCompression {
private static Scanner in;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner( System.in );
System.out.println( "Please input a string: " );
String str = in.nextLine();
String str1 = compressString( str );
System.out.println( str1);
}
public static String compressString( String str ) {
String strCompressed = new String();
strCompressed += str.charAt( 0 );
int count = 1;
for ( int i = 1; i < str.length(); i++ ) {
if ( str.charAt( i ) != str.charAt( i - 1 ) ) {
strCompressed += count;
strCompressed += str.charAt( i );
count = 1;
}
else {
count++;
}
}
strCompressed += count;
if ( strCompressed.length() >= str.length() )
return str;
else
return strCompressed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment