码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Word Pattern

时间:2015-10-10 01:34:49      阅读:171      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!