Word Pattern | LeetCode problem 290

preview_player
Показать описание
Word Pattern
Leetcode problem number 290
Solution in JAVA

JAVA interview programming playlist:

#java #interviewquestions #leetcode
Рекомендации по теме
Комментарии
Автор

It's logic is almost same that's you already discussed in Isomorphic String problem. Again Thanks a lot.

sathiroy
Автор

This code finally accept all case in leetcode for this question:=>
public boolean wordPattern(String pattern, String s) {
HashMap<Character, String> hm = new HashMap<>();
Set<String> set = new HashSet<>();

String arr[] = s.split(" ");
if(pattern.length() != arr.length){
return false;
}
for(int i=0; i<pattern.length(); i++){
String word = arr[i];
char ch = pattern.charAt(i);

if(hm.containsKey(ch)){

return false;
}
}else{
if(set.contains(word)){
return false;
}else{
hm.put(ch, word);
set.add(word);
}
}
}
return true;
}

imtiyazali
Автор

Thanks for this beautiful explanation.

sathiroy
Автор

Thank you so much mam
Great explanation 👍👍👍

raadali
Автор

Sometimes you have to zoom out to see the whole code, or put it in github it's even better. Thanks anyway

roqyaquran
Автор

Hello Amrita,
I am getting only "false" as output trying the same code.
package org.leeetcode.problems;

import java.util.HashMap;
import java.util.Map;

public class WordPattern {

public static void main(String[] args) {

String pattern="abba";
String str="cat, dog, dog, cat";
System.out.println(isWordPattern(pattern, str));

}

private static boolean isWordPattern(String pattern, String s) {

String []str= s.split(" ");

Map<Character, String> hm = new HashMap<Character, String>();

if(pattern.length()!= str.length) {
return false;
}

for(int i=0;i<pattern.length();i++) {

char ch = pattern.charAt(i);
boolean containsKey = hm.containsKey(ch);

!containsKey) {
return false;
}

if(containsKey && !hm.get(ch).equals(str[i]))
{
return false;
}
else {
str[i]);
}
}
return true;

}

}
Please let me know the line number at which there is an error

mdniyazhashmi
Автор

how can i become a good software engineer to writing a code

Future_software_enginneer
Автор

Its not working for "abba" And "dog dog dog dog"

P.RAMANJIREDDY
Автор

hello hi i did it using the same method which u taught in isomorphic strings
but it is giving wrong answer would you pls check
class Solution {
public boolean wordPattern(String pattern, String s) {

return false;
HashMap<Character, String>l=new HashMap<>();

s=s.trim();
String a[]=s.split(" ");

for(int i=0;i<a.length;i++){



return false;

}
else{

if(l.containsValue(a[i]))
return false;

l.put(pattern.charAt(i), a[i]);

}


}

return true;



}
}

ramineninagajaswanth