程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> [LeetCode] Word Pattern

[LeetCode] Word Pattern

編輯:關於C++

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.

解題思路

用一個哈希表建立從pattern中字符到str中字符串的映射。 用一個集合表示str中字符串是否已作為值出現在哈希表中。
以下兩種情況為假:
哈希表中已存在key,但是對應的value值不一樣。 哈希表中不存在key,但是對應的值已作為其他key的value值。

實現代碼

C++:

// Runtime: 0 ms
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector words;
        istringstream iss(str);
        string temp;
        while (iss>>temp)
        {
            words.push_back(temp);
        }
        if (words.size() != pattern.size())
        {
            return false;
        }
        unordered_map mymap;
        set used;
        for (int i = 0; i < pattern.length(); i++)
        {
            if (mymap.find(pattern[i]) == mymap.end())
            {
                if (used.find(words[i]) == used.end())
                {
                    mymap[pattern[i]] = words[i];
                    used.insert(words[i]);
                }
                else
                {
                    return false;
                }
            }
            else if (mymap[pattern[i]].compare(words[i]) != 0)
            {
                return false;
            }
        }

        return true;
    }
};

Java:

// Runtime: 3 ms
public class Solution {
    public boolean wordPattern(String pattern, String str) {
        String words[] = str.split( );
        if (pattern.length() != words.length) {
            return false;
        }
        Map mymap = new HashMap();
        for (int i = 0; i < pattern.length(); i++) {
            if (!mymap.containsKey(pattern.charAt(i))) {
                if (!mymap.containsValue(words[i])) {
                    mymap.put(pattern.charAt(i), words[i]);
                }
                else {
                    return false;
                }
            }
            else if (!mymap.get(pattern.charAt(i)).equals(words[i])) {
                return false;
            }
        }

        return true;
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved