1859. Sorting the Sentence

This problem can be solved by bicket sorting. Although the problem only requires the number is 1~9, but my solution can be extended to any number sentences:

class Solution {
    public String sortSentence(String s) {
        String[] strs = s.split(" ");
        String[] bucket = new String[strs.length+1];
        
        for(int i=0;i<strs.length;i++){
            String[] sno = getStringnNumber(strs[i]);
            bucket[Integer.valueOf(sno[1])]=sno[0];
        }
        
        StringBuilder strb = new StringBuilder();
        for(int i=1;i<bucket.length;i++){
            strb.append(bucket[i]);
            strb.append(' ');
        }
        strb.deleteCharAt(strb.length()-1);
        return strb.toString();
    }
    
    private String[] getStringnNumber(String s){
        int i=s.length()-1;
        while(i>=0){
            if(Character.isDigit(s.charAt(i)))
                i--;
            else
                break;
        }
        String[] res = new String[2];
        res[0]=s.substring(0, i+1);
        res[1]=s.substring(i+1);
        return res;
    }
}

 

上一篇:vue.esm.js?efeb:628 [Vue warn]: Invalid prop: type check failed for prop "hello". Expected


下一篇:PAT 1144 The Missing Number (20 分)