leetcode290 word Pattern

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值