567. Permutation in String

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1's permutations is the substring of s2.

Example 1:

Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

Input: s1 = "ab", s2 = "eidboaoo"
Output: false

Constraints:

  • 1 <= s1.length, s2.length <= 104
  • s1 and s2 consist of lowercase English letters.

题目:给定两个字符串,求s2中是否包含s1的排列。重要信息是只包含小写字符

思路:可用两个vector记录s1和s2子序列的小写字符个数。比较两个vector,如果相等则返回true,代码:

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        if(s2.length() < s1.length()) return false;
        vector<int> r1(26, 0), r2(26, 0);
        for(int i = 0; i < s1.length()-1; i++){
            r1[s1[i] - 'a'] ++;
            r2[s2[i] - 'a'] ++;
        }
        r1[s1.back()-'a']++;
        for(int i = s1.length()-1; i < s2.length(); i++){
            r2[s2[i] - 'a'] ++;
            if(i >= s1.length()) r2[s2[i-s1.length()] - 'a']--;
            bool flag = true;
            for(int j = 0; j<26; j++){
                if(r1[j] != r2[j]){
                    flag = false;
                    break;
                }
            }
            if(flag) return true;
        }
        return false;
    }
};

time: O(N), space:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值