c++ string之substr()函数

本文介绍C++中string类的substr()方法使用,包括如何通过自定义split()函数实现字符串分割。并详细解析LeetCode 290 Word Pattern题目,提供一种解决方案,涉及模式匹配和哈希映射的实现。
摘要由CSDN通过智能技术生成

本节简单记录string中的substr()方法。参数有两个:pos和len;操作就是将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<string> words = split(str);
        
        if( pattern.size() != words.size() )
            return false;
        
        unordered_map<char, string> resultP;
        unordered_map<string, char> 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<string> split(string& s){
        
        vector<string> 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值