• 290. Word Pattern--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.

    Example 1:

    Input: pattern = "abba", str = "dog cat cat dog"
    Output: true
    Example 2:

    Input:pattern = "abba", str = "dog cat cat fish"
    Output: false
    Example 3:

    Input: pattern = "aaaa", str = "dog cat cat dog"
    Output: false
    Example 4:

    Input: pattern = "abba", str = "dog dog dog dog"
    Output: false
    Notes:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.

    1.思考

    • 首先将string str中的元素以空格为分界按顺序取出存放于vector中;
    • 再通过二重循环,将pattern中两两组队,并对比str中相同位置的元素是否相同;
    • 若pattern中相同,而str中不同,则return false;
    • 若pattern中不同,而str中相同,则return false;
    • 若遍历所有都没有返回值,则return true。

    2.实现
    Runtime: 0ms(100%)
    Memory: 9MB(6.09%)

    class Solution {
    public:
        bool wordPattern(string pattern, string str) {        
            int len = pattern.size();
            vector<string> st;
            
            int ln = str.size();
            string s = str;
            while(1){
                int pos = s.find(' ');
                if(pos>0){                
                    st.push_back(s.substr(0, pos));
                    s = s.substr(pos+1);
                }
                else{
                    st.push_back(s);
                    break;
                }
            }
            
            if(st.size() != len)
                return false;
            
            for(int i=0; i<len; i++){            
                for(int j=i+1; j<len; j++){
                    if(pattern[i] == pattern[j]){
                        if(st[i] != st[j]){
                            return false;
                        }
                    }
                    else{
                        if(st[i] == st[j]){
                            return false;
                        }                    
                    }
                }            
            }
            
            return true;        
            
        }
    };
    
  • 相关阅读:
    项目各方面的目标
    WPF : Imaging
    在Windows EndSession时, WPF的Shutdown()和Winforms的Application.Exit()都不可靠
    软件运行流程
    做事首先要想到的是责任和分配机制
    RhinoMocks : Stub和Mock的区别
    Visual Studio Marco : CollapseLogRegions
    使用C#实现顺序队列
    MVC 分页
    sql 行列转置(将行转换为列)
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/11236357.html
Copyright © 2020-2023  润新知