Thursday, March 29, 2012

Print Character Repetition In SameArray


Q. Program for any given string a   aaaabbbbcc, convert the given string in to a4b4c2 without using extra memory. ( Note that every character appears more than once in input string and the repeated characters are contiguous)

Source Code:
import java.util.Scanner;

public class PrintArraywithRepetation {

    /**
     * @param args
     * @author chandan
     * Given String aaaaabbbccccaaad print as a5b3c4a3d1 (Inplace without using Extra array)
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
       
        String input = s.next();

         int count=1;
        
        for(int i=0 ;i < input.length();i++){
  
            if(i < input.length()-1){
                if(input.charAt(i)!=input.charAt(i+1)){
                    System.out.print(input.charAt(i));
                    System.out.print(count);
                    count=1;
                }
                else
                    count++;
               
            }
            else if(i==input.length())
            {
                if(input.charAt(i)!=input.charAt(i-1)){
                    System.out.print(input.charAt(i));
                    System.out.print(count);
                    count=1;
                    }
                    else
                        count++;
               
            }
            else {
               
                System.out.print(input.charAt(i));
                 System.out.print(count);
                 count++;
            }
           
        }
   
    }

}
Note : Suggestion  are always welcome for better way to implement.



No comments:

Post a Comment