1

Here the pattern is a string and arr is an array of strings, and map here is a hashmap i.e HashMap<Character,String> map = new HashMap<>();

if (!map.get(pattern.charAt(i)).equals(arr[i]) {
    return false;
}

The above one is working. But what is wrong with the next one?

if (map.get(pattern.charAt(i))!=(arr[i])){
    return false;
}

This is a part of my solution for question no. 290 leetcode. When I use first if statement the whole code is working, but for the second version of if statement not all test cases are getting passed. Why so?

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] arr=s.split(" ");
        if (arr.length!=pattern.length()) {
            return false;
        }
        HashMap<Character,String> map = new HashMap<>();
        for (int i=0;i<arr.length;i++) {
            if (map.containsKey(pattern.charAt(i))){
                //**this line is my doubt**//
                if (!map.get(pattern.charAt(i)).equals(arr[i])){
                    return false;
                } else {
                    if (map.containsValue(arr[i])) {
                        return false;
                }
                 map.put(pattern.charAt(i),arr[i]);
            }
        }
        return true;
    }
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I don't use Java, so I'm wondering what does `map.get(pattern.charAt(i))` return? I'd guess `.equals()` is there for a reason. – afarrag Jan 02 '23 at 04:02
  • 1
    Does this answer your question? [String.equals versus ==](https://stackoverflow.com/questions/767372/string-equals-versus) – Ryednap Jan 02 '23 at 04:05
  • In java `equals` method is used to check if two `String` are equal characters by character but using `==` or `!=` means it's checking whether two variables point to the same memory location. Hope this helps. Also, this is a duplicate of this question please check here. [String.equals versus ==](https://stackoverflow.com/questions/767372/string-equals-versus) – Ryednap Jan 02 '23 at 04:03
  • thank you so much for clearing my doubt!! – Paurab Bhattacharjee Jan 02 '23 at 12:43

0 Answers0