本文共 1686 字,大约阅读时间需要 5 分钟。
https://leetcode-cn.com/problems/word-pattern/
给定一种规律 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 包含了由单个空格分隔的小写字母。class Solution { public boolean wordPattern(String pattern, String str) { String[] strs = str.split(" "); char[] pc = pattern.toCharArray(); if(strs.length != pc.length){ return false; } MapscMap = new HashMap<>(); int[] postion = new int[256]; for(int i = 0; i < pc.length; i++){ char c = pc[i]; String currentStr = strs[i]; Character ch = scMap.get(currentStr); if(ch != null ){ if(c != ch){ return false; } }else{ scMap.put(currentStr, c); } int p = postion[c]; if(p != 0){ String oldStr = strs[p - 1]; if(!oldStr.equals(currentStr)){ return false; } } postion[c] = i + 1; } return true; }}
O(N)
转载地址:http://glpkb.baihongyu.com/