ok, i m doing some cracking the coding interview questions just to improve a bit my skills. and it s not that bad!
look up my code; it works , but has testing printing.
the question itself : compress a string, example : aaa = a3, ab = a1b1, abc = a1b1c1 etc.
if the compressed string is longer then return original.
import java.util.* ;
public class ctci{
public static void main(String args[]){
String result = compressed("aa") ;
}
public static String compressed(String original_string){
if(original_string.length() <=2 ) return original_string ;
String compressed_string = "" ;
for(int i = 0 ; i < original_string.length() ; i++){
System.out.println("------------------------------------------------------------------------------------------------------------------------------ i : " + i ) ;
char current_char = original_string.charAt(i) ;
System.out.println("current char " + current_char) ;
int streak = 1 ;
while(i < original_string.length() -1 && current_char == original_string.charAt(i+1) ) {
System.out.println("streak len growing: " + streak + " and letter is : " + original_string.charAt(i+1)) ;
i++ ;
streak++ ;
}
//compressed_string += (current_char + "") + streak ;
compressed_string += String.valueOf(current_char) + streak ;
System.out.println( "streak ended, length of the streak " + streak + " ; and the new string is " + compressed_string ) ;
}
if(compressed_string.length() >= original_string.length()){System.out.println("original returned! " + original_string) ; return original_string ;}
else{System.out.println("compressed returned! " + compressed_string) ; return compressed_string ;}
}
}