LeetCode 567. 字符串的排列

201 阅读1分钟

567. 字符串的排列

难度 中等

给你两个字符串 s1s2 ,写一个函数来判断 s2 是否包含 s1 的排列。如果是,返回 true ;否则,返回 false

换句话说,s1 的排列之一是 s2子串

示例 1:

输入:s1 = "ab" s2 = "eidbaooo"
输出:true
解释:s2 包含 s1 的排列之一 ("ba").

示例 2:

输入:s1= "ab" s2 = "eidboaoo"
输出:false

提示:

  • 1 <= s1.length, s2.length <= 104
  • s1s2 仅包含小写字母

题解

暴力枚举

本题可以采用枚举去解题,只要求s2中包含长度为s1的排列组合,采用循环+打表枚举+失败回溯。先遍历s1,新建个表格记录每个字母出现多少次;然后开始遍历s2,采用失败回溯方法,遍历到字符串末尾。

  • 遍历s1,记录每个字母出现次数

  • 遍历s2,比较每个字母出现的次数

    • 如果超过了s1中的字母,回溯
    • 没有超过s1中的字母,继续枚举
  • 如果枚举长度等于s1长度,返回true

  • 枚举结束都找不到,返回false

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int len1 = s1.size();
        int len2 = s2.size();
        int word[256] = {0};
        int c;
        for(int i = 0; i < len1; i++){//遍历s1
            c = int(s1[i]);
            word[c]++;//记录每个字母出现多少次
        }
        int newWord[256] = {0};
        int len = 0;
        for(int i = 0; i < len2; i++){//遍历s2
            c = int(s2[i]);
            newWord[c]++;
            if(newWord[c] > word[c]){//当某个字母超过了s1中的字母,枚举失败
                for(int j = 0; j < 256; j++){
                    newWord[j] = 0;
                }
                i = i - len;//回溯
                len = 0;
            }else{//没有超过s1中的字母,继续枚举
                len++;
                if(len == len1){//当枚举长度等于s1的长度,返回true
                    return true;
                }
            }
        }
        return false;//s2中找不到这样的枚举,返回false
    }
};

滑动窗口法

当我们在枚举的时候,我们都是从左往右枚举的,有什么办法不需要回溯呢,那应该是滑动窗口法了,但是滑动窗口法需要解决重复字符串的问题。官方采用hashset判断是否重复,如果不重复可以一直往右枚举;如果重复就需要一直删除到没有重复为止。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> occ = new HashSet<Character>();//去重
        int n = s.length();//字符串长度
​
        int rk = -1;//右指针
        int ans = 0;
        for(int i = 0; i < n; i++){//左指针
            if(i != 0){//删除重复字母
                occ.remove(s.charAt(i - 1));
            }
            while(rk + 1 < n && !occ.contains(s.charAt(rk + 1))){//如果没有包含这个字母,一直枚举
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            ans = Math.max(ans, rk - i + 1);//更新最大长度
        }
        return ans;
    }
}

\