leetcode-bytedance-字符串的排列

♀尐吖头ヾ 提交于 2020-01-07 21:56:55

在这里插入图片描述
满脑子都是暴力法:结果就超时了

一开始这么想的,就生成所有的由s1的组合,然后依次去s2中寻找是否有匹配的。

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        all_str = self.get_all_str(s1)
        for i in all_str:
            try:
                s2.index(i)
                return True
            except :
                pass
        return False

    def get_all_str(self,s):
        all_res = []
        def fun(s, res=""):
            if len(s) == 0:
                all_res.append(res)
            else:
                temp = s[:]
                for i in range(len(s)):
                    fun(temp[0:i] + temp[i + 1:], res + s[i])
        fun(s)
        return list(set(all_res))

超时,另外发现求字符串全部的排列可以使用交换位置法

    def get_all_res(str_,num = 0):
        if num ==len(str_):
            all_res.append("".join(str_))
        for i in range(num,len(str_)):
            temp = swap(str_, 0, i)
            get_all_res(str_,num+1)


    def swap(arr,i,j):
        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
        return arr


    get_all_res(["a","b","c"])
    print(all_res)

最终的答案滑动窗口法

public class Solution {
    public boolean checkInclusion(String s1, String s2) {
        if (s1.length() > s2.length())
            return false;
        int[] s1map = new int[26];
        int[] s2map = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            s1map[s1.charAt(i) - 'a']++;
            s2map[s2.charAt(i) - 'a']++;
        }
        for (int i = 0; i < s2.length() - s1.length(); i++) {
            if (matches(s1map, s2map))
                return true;
            s2map[s2.charAt(i + s1.length()) - 'a']++;
            s2map[s2.charAt(i) - 'a']--;
        }
        return matches(s1map, s2map);
    }
    public boolean matches(int[] s1map, int[] s2map) {
        for (int i = 0; i < 26; i++) {
            if (s1map[i] != s2map[i])
                return false;
        }
        return true;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/permutation-in-string/solution/zi-fu-chuan-de-pai-lie-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

体会体会思想

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!