zoukankan      html  css  js  c++  java
  • 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:

    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:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

    链接: http://leetcode.com/problems/word-pattern/

     1 public class Solution {
     2     public boolean wordPattern(String pattern, String str) {
     3         String[] parts = str.split(" ");
     4         if (pattern.length() != parts.length) return false;
     5         HashMap<Character, String> hcs = new HashMap<Character, String>();
     6         HashMap<String, Character> hsc = new HashMap<String, Character>();
     7 
     8         for(int i = 0; i < parts.length; i++) {
     9             if (!hsc.containsKey(parts[i]) && !hcs.containsKey(pattern.charAt(i))) {
    10                 hsc.put(parts[i], pattern.charAt(i));
    11                 hcs.put(pattern.charAt(i), parts[i]);
    12             } else if (hsc.containsKey(parts[i]) && hcs.containsKey(pattern.charAt(i)) && hsc.get(parts[i]) == pattern.charAt(i) && hcs.get(pattern.charAt(i)).equals(parts[i])) {
    13                 continue;
    14             } else {
    15                 return false;
    16             }
    17         }
    18         return true;        
    19     }
    20 }
  • 相关阅读:
    POJ 1044: Date bugs
    POJ 1017: Packets
    POJ 1014: Dividing
    POJ 1012: Joseph
    POJ 1011: Sticks
    POJ 1008: Maya Calendar
    POJ 1005: I Think I Need a Houseboat
    为什么要自动化测试
    微软CodeDom模型学习笔记(全)
    概念完整性
  • 原文地址:https://www.cnblogs.com/panini/p/6517647.html
Copyright © 2011-2022 走看看