Bit manipulation solution Java


  • 3
    Y
    public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<String>();
        int maxLen = 1<<word.length();
        for(int i=0;i<maxLen;i++){
            result.add(getString(i,word));
        }
        return result;
    }
    public String getString(int num,String word){
        StringBuilder sb = new StringBuilder();
        int count = 0;
        for(int i=0;i<word.length();i++){
            int bit = (num>>i)&1;
            if(bit==1){
                if(count!=0){
                    sb.append(count);
                    count = 0;
                }
                sb.append(word.charAt(i));
            }else{
                count+=1;
            }
        }
        if(count!=0)
            sb.append(count);
        return sb.toString();
    }
    

    }


Log in to reply
 

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