• 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.

    1. public class Solution {
    2. public bool WordPattern(string pattern, string str) {
    3. string[] strArr = str.Split(' ');
    4. if (pattern.Length != strArr.Length || (pattern.Length == 0 && str.Length == 0)) {
    5. return false;
    6. }
    7. Dictionary<char, string> dict = new Dictionary<char, string>();
    8. for (var i = 0; i < pattern.Length; i++) {
    9. if (dict.ContainsKey(pattern[i]) || dict.ContainsValue(strArr[i])) {
    10. string s = null;
    11. dict.TryGetValue(pattern[i], out s);
    12. if (s == strArr[i]) {
    13. continue;
    14. } else {
    15. return false;
    16. }
    17. } else {
    18. dict[pattern[i]] = strArr[i];
    19. }
    20. }
    21. return true;
    22. }
    23. }







  • 相关阅读:
    八月二十九学习报告
    文本操作
    EL表达式
    注解开发
    逆向
    内置对象和方法
    每日日报2020.11.10 1905
    每日日报2020.11.12 1905
    每日日报2020.11.17 1905
    每日日报2020.11.20 1905
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/ae8163108142c6ea7777b74645a888ea.html
Copyright © 2020-2023  润新知