Why my code does not work?


  • 0
    A
    public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        String temp = "";
        char [] c = s.toCharArray();
        
        for(int i =0; i< c.length; i++){
            temp = temp+c[i];
            
            if(wordDict.contains(temp) == true){
                temp = "";
            }
        }
        return temp == "";
    }
    

    }

    //Why my code fail the {"aaaa", "aaa"} case?
    //Having trouble understand the question...


  • 0
    P

    your solution is a kind of greedy algorithm.
    say s = "aaaa" dict=["aaa","aaaa"]
    when i==3 ,you left the last 'a', but you can't find it in the dictionary.it will return false.but s is in the dictionary.
    so your solution is wrong


  • 1
    P

    your solution is a kind of greedy algorithm.

    say s = "aaaa" dict=["aaa","aaaa"]
    when i==3 ,you left the last 'a', but you can't find it in the dictionary.it will return false.but s is in the dictionary.

    so your solution is wrong


  • 0
    A

    Make sense!
    Thanks


Log in to reply
 

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