单词规律
- 给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。(ps:就是字符和空格分隔出来的字符串映射)
示例1:
输入: pattern = “abba”, s = “dog cat cat dog”
输出: true
示例 2:
输入:pattern = “abba”, s = “dog cat cat fish”
输出: false
解题思路
- 遍历字符串和规律,同时维护两个映射关系, 用于记录字符到字符串的映射和字符串到字符的映射。
- 在遍历的过程中,检查当前字符与字符串的映射关系是否相符,若不相符则返回 false。
Java实现
public class WordPattern {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (pattern.length() != words.length) {
return false;
}
Map<Character, String> charToStr = new HashMap<>();
Map<String, Character> strToChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
//字符映射到字符串要一一对应
if (!charToStr.containsKey(c)) {
charToStr.put(c, word);
} else {
if (!charToStr.get(c).equals(word)) {
return false;
}
}
//字符串映射到字符也要一一对应
if (!strToChar.containsKey(word)) {
strToChar.put(word, c);
} else {
if (strToChar.get(word) != c) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
WordPattern wordPattern = new WordPattern();
// Test Case 1
String pattern1 = "abba";
String s1 = "dog cat cat dog";
System.out.println("Test Case 1:");
System.out.println("pattern: \"" + pattern1 + "\", s: \"" + s1 + "\"");
System.out.println("Result: " + wordPattern.wordPattern(pattern1, s1)); // Expected: true
// Test Case 2
String pattern2 = "abba";
String s2 = "dog cat cat fish";
System.out.println("\nTest Case 2:");
System.out.println("pattern: \"" + pattern2 + "\", s: \"" + s2 + "\"");
System.out.println("Result: " + wordPattern.wordPattern(pattern2, s2)); // Expected: false
}
}
时间空间复杂度
- 时间复杂度: 遍历规律和字符串,时间复杂度为 O(n),其中 n 是字符串的长度。
- 空间复杂度:使用了两个HashMap来存储字符到字符串的映射和字符串到字符的映射,空间复杂度为O(n),其中n 是字符串的长度。