Alternate approach


  • 0
    P

    Alternate approach in Java.

    
    class Solution {
        public String replaceWords(List<String> dict, String sentence) {
            if (sentence == null || sentence.equals("")) {
                return sentence;
            } 
    
            Collections.sort(dict);
            String[] array = sentence.split(" ");
            for (String word : dict) {
                for (int i = 0; i < array.length; i++) {
                    if (array[i].startsWith(word)) {
                        array[i] = word;
                    }
                }
            }
    
            return String.join(" ", array);
        }
    }```

Log in to reply
 

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