Created
April 17, 2013 18:08
-
-
Save astkaasa/5406441 to your computer and use it in GitHub Desktop.
problem 1.5
This file contains 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
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