首页 > 其他 > 详细

[Leetcode] Word Pattern

时间:2015-10-10 01:34:12      阅读:370      评论:0      收藏:0      [点我收藏+]

题目如下。~

Given a pattern and a string str, find if str follows the same pattern.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

 

Notes:

  1. patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
  2. Both pattern and str do not have leading or trailing spaces.
  3. Each letter in pattern must map to a word with length that is at least 1.

 

这题没啥难度。主要是要把逻辑搞清楚。借助hashset来做是最方便的。

至于设置几个hashset,可以用一个也可以用两个,反正看自己的习惯。

代码如下。~

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        
        HashSet<Character> chara=new HashSet<>();
        HashSet<String> stri=new HashSet<>();
        String[] temp=str.split(" ");
        if(pattern.length()!=temp.length){
            return false;
        }
        for(int i=0;i<pattern.length();i++){
            if(chara.contains(pattern.charAt(i))){
                if(!stri.contains(temp[i])){
                    return false;
                }
                chara.remove(pattern.charAt(i));
                stri.remove(temp[i]);
            }else{
                if(stri.contains(temp[i])){
                    return false;
                }
               chara.add(pattern.charAt(i));
               stri.add(temp[i]);
            }
        }
        return true;
        
    }
}

 

[Leetcode] Word Pattern

原文:http://www.cnblogs.com/orangeme404/p/4865553.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!