Leetcode 290 word Pattern
这题是按我自己思路写的,可能不是最优的代码,期望能对大家有一点点帮助。
题目:
Given a pattern and a string str, find if str 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 str.
Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
我的思路大致是这样的,把str分割成字符串数组{“dog”,”cat”,”cat”,”dog”},然后遍历这个字符串数组strs,如果pattern和strs对应位置,都不存在于字典和hash中,就将其存进去,否则判断是否相等。代码如下:
class Solution {
public boolean wordPattern(String pattern, String str) {
String[] strs=str.split(" ");
Map<Character,String> hash=new HashMap<>();
Trie trie=new Trie();
if(strs.length!=pattern.length()) return false;
for(int i=0;i<strs.length;i++){
if(hash.containsKey(pattern.charAt(i))){
boolean boo=hash.get(pattern.charAt(i)).equals(strs[i]);
if(boo==false) return false;
}else{
if(trie.search(strs[i])){
return false;
}else{
hash.put(pattern.charAt(i),strs[i]);
trie.insert(strs[i]);
}
}
}
return true;
}
}
//下面是字典树的构造过程,有需要的童鞋可以看看
//字典树查找字符串的效率是比较高的
class Trie{
Node root;
public Trie(){
root=new Node(' ');
}
public boolean search(String word){
Node current=root;
for(char c:word.toCharArray()){
Node child=current.childNode(c);
if(child==null) return false;
current=child;
}
return current.isEnd;
}
public void insert(String word){
Node current=root;
for(char c:word.toCharArray()){
Node child=current.childNode(c);
if(child==null){
child=new Node(c);
current.childList.add(child);
}
current=child;
}
current.isEnd=true;
}
}
class Node{
char content;
boolean isEnd;
List<Node> childList;
public Node(char c){
content=c;
isEnd=false;
childList=new LinkedList<>();
}
public Node childNode(char c){
Iterator<Node> it=childList.iterator();
while(it.hasNext()){
Node node=it.next();
if(node.content==c) return node;
}
return null;
}
}