My 4ms java Solution


  • 0
    3
    public class Solution {
           ArrayList<String> strs = new ArrayList<>();
        String[] smap={" ","._@/#","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        /*本方法用于根据对应位置的索引序号拼接字符串,并把拼接后的字符串添加到结果中*/
        private void selects(List<String> list,int [] count,int len){
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<len;i++){
                String temp=list.get(i).substring(count[i],count[i]+1);
                sb.append(temp);
            }
            strs.add(sb.toString());
        }
        /*本方法用于进位*/
        private void goahead(List<Integer> numstrlen, int []count,int len){
            int index=len-1;
            while(count[index]==numstrlen.get(index)&&index!=0){
                count[index]=0;
                count[--index]++;
            }
        }
        public List<String> letterCombinations(String digits) {
            if(digits.length()==0) return strs;
            int [] count=new int[digits.length()];
            int len=digits.length();
            ArrayList<String> numstrs = new ArrayList<>();
            ArrayList<Integer> numstrslen = new ArrayList<>();
            for(int i=0;i<len;i++){
                int temp=digits.charAt(i)-48;
                numstrs.add(smap[temp]);
                numstrslen.add(smap[temp].length());
            }
            int endS=numstrslen.get(0);
            while(count[0]<endS){
                selects(numstrs,count,len);
                count[len-1]++;
                goahead(numstrslen,count,len);
            }
            return strs;
        }
    }

Log in to reply
 

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