Leetcode 567. 字符串的排列

 超时解:

基本思路:首先在s2中找到s1的所有字母中第一个出现的位置,比如

s1 = "ab" s2 = "eidbaooo"

我在s2中进行遍历,找第一出现的s1中的字母,也就是下标为3的‘b’,找到之后,从‘b’起始,截取s1的长度的那么一段,扔到函数checkInclusion2中进行比较。

函数checkInclusion2的比较方式为hashmap比较法(我自己取的名字),将每一个字母出现的次数记录到一个hashmap中,再对该hashmap进行比较即可。

结果超时了,在第一步找第一个位置的时候 时间复杂度为 O(n*m)。n为s1长,m为s2长。 从这入手优化一下

class Solution {
public:
	bool checkInclusion(string s1, string s2) {
        if (s1.size() > s2.size())
			return false;
		int Len = s1.size();
		for (int i = 0; i <= s2.size()-Len; i++)
		{
			for (int j = 0; j < s1.size(); j++)
			{
				if (s1[j] == s2[i])
				{
					string Temp(s2.begin()+i, s2.begin()+i + Len);
					if (checkInclusion2(s1, Temp))
						return true;
				}
			}
		}
		return false;
	}

	bool checkInclusion2(string s1, string s2)
	{
		int S1[26], S2[26];
		memset(S1, 0, sizeof(S1));
		memset(S2, 0, sizeof(S2));
		for (int i = 0; i < s1.size(); i++)
		{
			S1[(s1[i] - 97)]++;
			S2[(s2[i] - 97)]++;
		}
		for (int i = 0; i <26; i++)
		{
			if (S1[i] != S2[i])
				return false;
		}
		return true;
	}
};

AC解

首先找到s1中的有哪些字符出现了。

再在s2中进行遍历,若发现某个字符在s1中出现,那么就按照上面的方式进行截取,然后扔到checkInclusion2中进行比较。

class Solution {
public:
	bool checkInclusion(string s1, string s2) {
		if (s1.size() > s2.size())
			return false;
		int Len = s1.size(),Temp[26];
		memset(Temp, 0, sizeof(Temp));
		for (int i = 0; i < Len; i++)
		{
			Temp[(s1[i] - 97)]++;
		}

		for (int i = 0; i <= s2.size() - Len; i++)
		{
			if (Temp[(s2[i] - 97)] > 0)
			{
				string Temp(s2.begin() + i, s2.begin() + i + Len);
				if (checkInclusion2(s1, Temp))
					return true;
			}
		}
		return false;
	}

	bool checkInclusion2(string s1, string s2)
	{
		int S1[26], S2[26];
		memset(S1, 0, sizeof(S1));
		memset(S2, 0, sizeof(S2));
		for (int i = 0; i < s1.size(); i++)
		{
			S1[(s1[i] - 97)]++;
			S2[(s2[i] - 97)]++;
		}
		for (int i = 0; i <26; i++)
		{
			if (S1[i] != S2[i])
				return false;
		}
		return true;
	}
};

牛批解:  该解法是Leetcode提交解答中速度最快的一个代码,将其拷贝下来作为学习之用,侵删。

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int len1=s1.length(),len2=s2.length();
        if(len1>len2) return false;
        vector<int> S(26);
        vector<int> V(26);
        for(int i=0;i<len1;i++){
            S[s1[i]-97]++;
            V[s2[i]-97]++;
        }
        for(int i=0;i<len2-len1+1;i++){
            if(S==V) return true;
            if(i<len2-len1){
                V[s2[i]-97]--;
                V[s2[i+len1]-97]++;
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/liaoxuda_edu/article/details/81476926