c++stringのsubstr()関数

2372 ワード

このセクションではstringのsubstr()メソッドを簡単に記録します.パラメータはposとlenの2つです.string[pos,pos+len]位置文字「スライス」をサブ文字列にする操作です.PS:c++にはsplit()メソッドはないのでstringのサブ文字列を得るためにはsplit()関数を独自に構築する必要がある.https://zh.cppreference.com/w/cpp/string/basic_string/substr https://blog.csdn.net/sunshihua12829/article/details/50484966
運用:Leetcode 290.Word 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.
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        
        vector words = split(str);
        
        if( pattern.size() != words.size() )
            return false;
        
        unordered_map resultP;
        unordered_map resultS;
        for( int i = 0; i < pattern.size(); i++ ){
            if( resultP.find(pattern[i]) == resultP.end() ){
                **//eg: pattern = {"abba"}, str = {"dog dog dog dog"}**
                if( resultS.find(words[i]) != resultS.end() )
                    return false;
                
                resultP[pattern[i]] = words[i];
                resultS[words[i]] = pattern[i];
            }
            else{
                string s = resultP[pattern[i]];
                if( s != words[i] )
                    return false;
            }
                
        }
        
        return true;
        
    }
    
private:
    vector split(string& s){
        
        vector res;
        
        int start = 0;
        for( int i = start+1; i <= s.size(); ){
            if( i == s.size() || s[i] == ' ' ){
                res.push_back(s.substr(start, i-start));
                start = i + 1;
                i = start + 1;
            }
            else
                i++;
        }
        
        return res;
    }
};