zoukankan      html  css  js  c++  java
  • 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;        
            
        }
    };
    
  • 相关阅读:
    Salesforce 大量数据部署的最佳实践
    Salesforce 数据备份和恢复小知识
    Salesforce 导入导出数据简介
    GDPR 和个人信息保护的小知识
    代码审查要点简介
    Salesforce 外部对象
    Python scipy.sparse.csr_matrix()[csc_matrix()]
    Deep Compression
    Pascal voc api
    Python内置模块-xml模块
  • 原文地址:https://www.cnblogs.com/xuyy-isee/p/11236357.html
Copyright © 2011-2022 走看看