My concise soluting using Bit manipulation


  • 0
    L
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<>();
        int n = word.length();
        word = word +"a";
        for(int i=0;i<(1<<n);i++){
            StringBuilder sb = new StringBuilder();
            int d=i,count=0;
            for(int j=0;j<=n;j++){
                if((d&1)==1) count++;
                else{
                    if(count>0) sb.append(count);
                    count=0;
                    sb.append(word.charAt(j));
                }
                d >>=1;
            }
            sb.setLength(sb.length() - 1);
            result.add(sb.toString());
        }
        return result;
    }
    

    I code abbreviation as 1 and no-abbreviation as 0. There are pow(2,n) ways of generalized abbrevations. But my solution only beats 40% JAVA solutions. Is there any improvement?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.