Simple Java solution with comments


  • 0
    A
    public class Solution {
        public String replaceWords(List < String > dict, String sentence) {
            int l = dict.size(), m = sentence.length();
            HashSet < String > hs = new HashSet < > ();
    
            for (int i = 0; i < l; i++) {
                String str = dict.get(i);
                if (!hs.contains(str)) {
                    hs.add(str);
                }
            }
    
            StringBuilder sb = new StringBuilder("");
    
            char[] stc = sentence.toCharArray();
            //Loop over all the words in the given sentence word by word
            //loop over the current word char by char, by storing the resulting string in temp
            //checking if the substring is present in dictionary using HashSet
            //if its present add it to the answer and skip rest of the chars in the current word
            for (int i = 0; i < m; i++) {
                char c = stc[i];
                if (c == ' ') {
                    sb.append(c);
                } else {
                    String temp = "";
                    int j = i + 1, k = j;
                    boolean flag = false;
                    for (j = i; j < m && stc[j] != ' '; j++) {
                        char d = stc[j];
                        temp += d;
                        // Found the shortest root
                        //add the root in stringbuilder sb and skip the rest of the chars in the word
                        if (hs.contains(temp)) {
                            sb.append(temp);
                            flag = true;
                            k = j + 1;
                            //to skip the rest of the chars in the current word
                            for (k = j + 1; k < m; k++) {
                                if (stc[k] == ' ') {
                                    break;
                                }
                            }
                            i = k - 1;
                            break;
                        }
                    }
                    //if we did not find the current word in the dictionary
                    // add the complete word to the stringbuilder sb
                    if (!flag) {
                        //j is the next posion of ' '
                        i = j - 1;
                        sb.append(temp);
    
                    }
                }
            }
    
            return sb.toString();
        }
    }
    

Log in to reply
 

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