其他分享
首页 > 其他分享> > 1859. Sorting the Sentence

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;
    }
}

 

标签:1859,Sorting,String,Sentence,strs,res,number,substring,new
来源: https://www.cnblogs.com/feiflytech/p/15894910.html