Word Break case failing for case "a",["a"]


  • 0
    P

    This is failing for case "a" ,["a"] here..but when i checked in eclipse its working..whats wrong with this.

    public boolean wordBreak(String s, Set<String> dict) {

        boolean flag= false;
        if(!dict.isEmpty()){
    		String[] tempArr = dict.toArray(new String[0]);
    		if(tempArr.length ==1){
    			if(s == tempArr[0]){
    				flag = true;
    			}
    		}
    		else{
    			for(int i=0;i<tempArr.length;i++){
    				if(s.contains(tempArr[i])){
    					s=s.substring(0,tempArr[i].length());
    				}
    				if(s.length()==0){
    					flag = true;
    				}
    			}
    		}
    	}
    	return flag;
        
        
    }

  • 2
    M

    What is happening in your code is an artifact of how strings are created in Java. Based off of your report of the answer, your tester code looks like this:

    String s = "a";
    Set<String> dict = {"a"};
    System.out.println(sol.wordBreak(s,dict));
    

    In your solution, you are comparing the strings using '==', which, for objects, compares the addresses the object is stored at, in other words, is it the same object, not just the same content. For example, imagine you have 2 Person objects, each containing the name of the person. == returns whether or not it is the same person, instead of just 2 people with the same name.

    The problem here is that Java has a nice trick when it comes to string literals (String s = "hello";) rather than String creation (String s = new String("hello");). When a String is created using literals, at the compile time, a String object is created and stored using String.intern(), and the assignment is made using that object. When you make another String using an equivalent literal, it reuses the same object, not creating a new one.

    String creation using new, on the other hand, always generates a new String object, so ==, which compares object addresses, rightfully reports that it is not the same object. .equals(), which compares the content, looks at the values in the Strings, sees they are the same, and reports the strings have the same values.

    Since you use the literal "a" in both parts of the tester, the same object is returned both times. However, leetcode knows this, and so likely has the tester creating Strings the long way, using new String("a");. Because of this difference, == works in your code, and fails in leetcode's.

    In short, to solve your problem, change

    if(s == tempArr[0]){
    

    to

    if(s.equals(tempArr[0])){
    

    and it will work. Just remember, == compares if it's the same object, while .equals compares if the objects have the same content.

    P.S. There is a nice discussion about this over on Stack Overflow.


Log in to reply
 

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