🎀 The Problem
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
👩💻 My Answer
class Solution {
public boolean wordPattern(String pattern, String s) {
HashMap map = new HashMap();
int count = 0, wordcount = 0;
String word = "";
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
if (count == pattern.length())
return false;
if (letter != ' ')
word += letter;
if (i == s.length() - 1 || word != "" && letter == ' ' ){
char key = pattern.charAt(count);
if (!map.containsKey(key))
if (!map.containsValue(word)) {
map.put(key, word);
wordcount++;
}
else
return false;
else if (map.containsKey(key))
if (!map.get(key).equals(word))
return false;
else
wordcount++;
count++;
word = "";
}
}
if (wordcount != pattern.length())
return false;
return true;
}
}
Pro & Con
- ✖️ Runtime & Memory
💋 Ideal Answer
Approach
Ok, I did not know there is a library that can split words by " " and store them into the String[]. This lack of knowledge costs me so many lines and runtime.
Here is my new code that BEATS 100%.
New Code
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length())
return false;
HashMap map = new HashMap();
for (int i = 0; i < words.length; i++) {
char key = pattern.charAt(i);
if (!map.containsKey(key) && !map.containsValue(words[i]))
map.put(key, words[i]);
else if (map.containsKey(key) && map.get(key).equals(words[i]))
continue;
else
return false;
}
return true;
}
}
💡 What I Learned
- How to separate the string by word and store them in a String[].
String[] words = STRING_NAME.split(" ");
Top comments (0)