LeetCode 290. Word Pattern Solution Explained - Java

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

map.containsValue has O(N) time complexity if instead of 1 Map you use 2 Maps you can improve the time complexity while sacrificing the space

NoWarForever
Автор

One thing I had an issue with here was that the pattern length must equal the string length. I passed the leetcode problem before coming here, but it was the last issue I went into. The question is ambiguous. If it is a pattern, there is no reason the string cannot be longer. For example "abba" and "dog cat cat dog dog cat cat dog". In my original solution to the problem, I accounted for this.... the sentence still "fits" the pattern. The problem does not accept this, however, and I removed it and passed the leetcode problem easily. The reason I comment is, if you are asked this in an interview or something, be prepared to ask whether the pattern can recur or if its length is an actual integral part (in which case, it really isn't a pattern so much as simply a one-to-one mapping).

wolfofthelight
Автор

Tried this same algorithm using the c++ was not able to get it but now it seems easy...

pushpendrasingh
Автор

Thank you. it is clean and easy to understand

samandarboymurodov
Автор

doest looks a "easy " problem to me

ramsharma
Автор

class Solution {
public boolean wordPattern(String pattern, String str) {
String []sa=str.split(" ");
if(pattern == null || sa.length!=pattern.length())
return false;

int n=pattern.length();
Map<Character, Integer> m=new HashMap<>();
Map<String, Integer> m1=new HashMap<>();

for(int i=0;i<n;i++)
{
char ch=pattern.charAt(i);
String s=sa[i];

if(m.containsKey(ch) && m1.containsKey(s))
{
if(m.get(ch)!=m1.get(s))
return false;
}
else if(m.containsKey(ch) || m1.containsKey(s))
return false;

m.put(ch, i+1);
m1.put(s, i+1);
}
return true;
}
}

what's the mistake in this code can u please tell

sriramsatvikatukuri
Автор

It's a request please don't use Java ....use c++ in your videos🙏🙏🙏🙏🙏🙏

aayushpagare