zoukankan      html  css  js  c++  java
  • Word Pattern

    Total Accepted: 18003 Total Submissions: 66490 Difficulty: Easy

    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.

    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<char,string> c_str_map;
            unordered_map<string,char> str_c_map;
            istringstream iss(str);
            string word;
            int i=0;
            while(i<pattern.size() && iss>>word ){
                char c = pattern[i++];
                if(i==0){
                    c_str_map[c] = word;
                    str_c_map[word] = c;
                }else{
                    string map_str = c_str_map[c];
                    char map_c = str_c_map[word];
                    if(map_str == "" && map_c==''){
                        c_str_map[c] = word;
                        str_c_map[word] = c;
                    }else if(map_str!=word || map_c!=c){
                        return false;
                    }
                }
            }
            if(i==pattern.size() && iss.eof()){
                return true;
            }
            return false;
        }
    };
    /*
    "a"
    ""
    
    "a"
    "word"
    
    "a"
    "word word"
    
    "ab"
    "word"
    
    "ab"
    "word word"
    
    "ab"
    "word sek"
    
    "aba"
    "word sek word"
    */
  • 相关阅读:
    CocoaPods使用详细说明
    UICollectionView的使用小记录和一些说明
    UICollectionView的使用
    ios获取UserAgent
    获取广告标识符ifad
    iOS获取UUID,并使用keychain存储
    振动一次
    CocoaPods本身版本的更新
    3D Touch集成过程整理
    iOS开发-UI (三)Collection
  • 原文地址:https://www.cnblogs.com/zengzy/p/5050838.html
Copyright © 2011-2022 走看看