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;
}
}