Java compressing Strings

前端 未结 20 1018
误落风尘
误落风尘 2020-11-29 09:24

I need to create a method that receives a String and also returns a String.

Ex input: AAABBBBCC

Ex output: 3A4B2C

Well, this is quite embarrassing a

相关标签:
20条回答
  • 2020-11-29 10:18

    The easiest approach:- Time Complexity - O(n)

    public static void main(String[] args) {
        String str = "AAABBBBCC";       //input String
        int length = str.length();      //length of a String
    
        //Created an object of a StringBuilder class        
        StringBuilder sb = new StringBuilder(); 
    
        int count=1;   //counter for counting number of occurances
    
        for(int i=0; i<length; i++){
            //if i reaches at the end then append all and break the loop
            if(i==length-1){         
                sb.append(str.charAt(i)+""+count);
                break;
            }
    
            //if two successive chars are equal then increase the counter
            if(str.charAt(i)==str.charAt(i+1)){   
                count++;
            }
            else{
            //else append character with its count                            
                sb.append(str.charAt(i)+""+count);
                count=1;     //reseting the counter to 1
            }
       }
    
        //String representation of a StringBuilder object
        System.out.println(sb.toString());   
    
    }
    
    0 讨论(0)
  • 2020-11-29 10:22

    O(n) approach

    No need for hashing. The idea is to find the first Non-matching character. The count of each character would be the difference in the indices of both characters.

    for a detailed answer: https://stackoverflow.com/a/55898810/7972621

    The only catch is that we need to add a dummy letter so that the comparison for the last character is possible.

    private static String compress(String s){
        StringBuilder result = new StringBuilder();
        int j = 0;
        s = s + '#';
        for(int i=1; i < s.length(); i++){
            if(s.charAt(i) != s.charAt(j)){
                result.append(i-j);
                result.append(s.charAt(j));
                j = i;
            }
        }
       return result.toString();
    }
    
    0 讨论(0)
提交回复
热议问题