C/C++教程

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 the Sentence的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!