博主并没有什么算法基础,所以写的不好,勿喷,抛砖引玉,欢迎交流,感谢。
//给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
// 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
// 示例1:
// 输入: pattern = "abba", str = "dog cat cat dog"
//输出: true
// 示例 2:
// 输入:pattern = "abba", str = "dog cat cat fish"
//输出: false
// 示例 3:
// 输入: pattern = "aaaa", str = "dog cat cat dog"
//输出: false
// 示例 4:
// 输入: pattern = "abba", str = "dog dog dog dog"
//输出: false
// 说明:
//你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
// Related Topics 哈希表
// 👍 191 👎 0
package com.zqh.leetcode.editor.cn;
//Java:单词规律
public class P290WordPattern {
public static void main(String[] args) {
Solution solution = new P290WordPattern().new Solution();
System.out.println(solution.wordPattern("abba", "dog cat cat dog"));
System.out.println(solution.wordPattern("abba", "dog cat cat fish"));
System.out.println(solution.wordPattern("aaaa", "dog cat cat dog"));
System.out.println(solution.wordPattern("abba", "dog dog dog dog"));
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean wordPattern(String pattern, String s) {
char[] chars = pattern.toCharArray();
String[] sArray = s.split(" ");
if (chars.length != sArray.length) {
return false;
}
for (int i = 0; i < chars.length; i++) {
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
if (sArray[i].hashCode() != sArray[j].hashCode()) {
return false;
}
continue;
}
if (sArray[i].hashCode() == sArray[j].hashCode()) {
return false;
}
}
}
return true;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}