Simple Java Sort Solution


  • 1

    Sort the dictionary ascending order of length. The for each word in the sentence, just try to find the first match in the dictionary.

    public String replaceWords(List<String> dict, String sentence) {
        Collections.sort(dict, Comparator.comparingInt(a -> a.length()));
        String[] words = sentence.split("\\s");
        StringBuilder sb = new StringBuilder();
        
        for(String word : words) {
            for(String match : dict) {
                if(word.startsWith(match)) {
                    word = match;
                    break;
                }
            }
            sb.append(word + " ");
        }
        sb.replace(sb.length()-1, sb.length(), "");
        return sb.toString();
    }

Log in to reply
 

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