Word law
Title description: Given a pattern and a string str, judge whether str follows the same rule.
Follow here refers to complete matching. For example, there is a bidirectional connection between each letter in the pattern and each non-empty word in the string str.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/word-pattern/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: character matching
- First, get all the words of the string s and put them in a List strList (need to be excluded from the empty string);
- Then, determine whether the number of strList and the length of the pattern are the same. If they are not the same, it means that the rule cannot be followed, and false is returned directly.
Then, declare a Map, or mappings, to store the mapping relationship between the characters in the pattern and the words in strList, and to traverse the characters in the pattern, the specific process is as follows:
- If the current character is in the key of mappings and the current word of strList is different from the word mapped by the current character in the mapping, false is returned;
- If the current character is not in mappings, if the current word in strList is in the values set of mappings, false is returned; if the current word in strList is not in the values set of mappings, then the current character and the current word in strList are placed in mappings, and then continue Determine the next character.
- Finally, if no unmatched mapping relationship is found, it returns true.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LeetCode_290 {
public static boolean wordPattern(String pattern, String s) {
String[] strs = s.split(" ");
List<String> strList = new ArrayList<>();
for (String str : strs) {
if (str != "") {
strList.add(str);
}
}
// 判断strList的数量和pattern的长度是否相同,如果不相同,说明无法遵循规律,直接返回false
if (pattern.length() != strList.size()) {
return false;
}
Map<Character, String> mappings = new HashMap<>();
for (int i = 0; i < strList.size(); i++) {
if (mappings.keySet().contains(pattern.charAt(i))) {
if (!strList.get(i).equals(mappings.get(pattern.charAt(i)))) {
return false;
}
} else {
if (mappings.values().contains(strList.get(i))) {
return false;
}
mappings.put(pattern.charAt(i), strList.get(i));
}
}
return true;
}
public static void main(String[] args) {
System.out.println(wordPattern("abba", "dog dog dog dog"));
}
}
【Daily Message】 As long as there is heart, life will blossom.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。