Share my simple Java solution.


  • 0
    A
    class Solution {
        public String replaceWords(List<String> dict, String sentence) {
            StringBuilder result = new StringBuilder();
            int start = 0;
            int end = 0;
            while(end < sentence.length()){
                while( ( end < sentence.length() )&& sentence.charAt(end)!=' ')      //take one word from the sentence
                    end++;
                String word = sentence.substring(start,end);
                end++;
                start =end;
                
                for(String d : dict){
                    if(word.indexOf(d)==0){           
                        word = d;
                    }
                }
                result.append(word);
                result.append(' ');
            }
            result.delete(result.length()-1,result.length());
            return result.toString();
        }
    }
    

Log in to reply
 

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