Skip to content

Commit

Permalink
Create 290-word-pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
tharunkanna14 authored Nov 8, 2022
1 parent 914a2e4 commit 157ab60
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions java/290-word-pattern
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] sArray = s.split("\s");
if(sArray.length != pattern.length()) {
return false;
}

HashMap<Character,String> charToWord = new HashMap<>();
HashMap<String,Character> wordToChar = new HashMap<>();

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

if(charToWord.containsKey(pattern.charAt(i)) && !charToWord.get(pattern.charAt(i)).equals(sArray[i])) {
return false;
}

if(wordToChar.containsKey(sArray[i]) && !wordToChar.get(sArray[i]).equals(pattern.charAt(i))) {
return false;
}

charToWord.put(pattern.charAt(i),sArray[i]);
wordToChar.put(sArray[i],pattern.charAt(i));
}
return true;
}
}

0 comments on commit 157ab60

Please sign in to comment.