Basic Java solution using String object


  • 0
    I
        public String replaceWords(List<String> dict, String sentence) {
            String [] strArr = sentence.split(" ");
            String newStr = "";
            for(int j = 0; j<strArr.length; j++){
                for(int i=0; i<dict.size(); i++){
                    if(strArr[j].contains((String)dict.get(i)) && strArr[j].startsWith((String) dict.get(i))){
                        strArr[j] = (String) dict.get(i); 
                        break;
                    }
                    
                }
                if(j==strArr.length-1){
                    newStr += strArr[j];
                }else{
                    newStr += strArr[j]+" ";
                }
            }
            return newStr;
        }
    

Log in to reply
 

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