Simple java HashSet and Optimized beats 100 %


  • 0
    M
    public String replaceWords(List<String> dict, String sentence) {
            HashSet<String> hs=new HashSet<String>();
            int max=0;
            for(String each: dict){
                hs.add(each);
                max=Math.max(max,each.length());
            }
            String[] all=sentence.split(" ");
            StringBuilder sb=new StringBuilder();
            for(String each: all){
                for(int i=1;i<=each.length() && i<=max;i++){
                    if(hs.contains(each.substring(0,i))){
                        each=each.substring(0,i);
                        break;
                    }
                }
                sb.append(each+" ");
            }
            
            return sb.toString().trim();
        }
    

Log in to reply
 

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