字符串无序匹配实现

给定长度为m的字符串aim,以及一个长度为n的字符串str,问能否在str中找到一个长度为m的连续子串,使得这个子串刚好由aim的m个字符串组成,顺序无所谓,返回任意满足条件的一个子串的起始位置,未找到返回-1

/* 思路:
       创建一个数组count用于统计aim中的字符串出现的频率,
       利用滑动窗口在str上从左到右滑动,直到窗口走完整个str或者发现发现匹配的子串    (result==0)表示匹配成功 
   时间复杂度:O(n+m)
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int isUnorderedMatch(string& str, string& aim) {
    
    
	if (str.empty() || aim.empty() || str.length() < aim.length()) {
    
    
		return -1;
	}
	vector<int> count(128, 0);
	for (char ch : aim) {
    
    
		count.at(ch)++;
	}
	int i = 0;
	int result = 0;
	for (; i < aim.length(); i++) {
    
    
		if (count.at(str.at(i))-- == 0) {
    
    
			result++;
		}
	}
	for (; i < str.length(); i++) {
    
    
		if (result == 0) {
    
    
			return i - aim.length();
		}
		if (count.at(str.at(i))-- <= 0) {
    
    
			result++;
		}
		if (count.at(str.at(i - aim.length()))++ < 0) {
    
    
			result--;
		}
	}
	return result == 0 ? (i - aim.length()) : -1;
}

int main() {
    
    
	string str("akaafcbaabc");
	string aim("aabc");
	cout << isUnorderedMatch(str, aim) << endl;

	system("pause");
	return 0;
}

如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢

猜你喜欢

转载自blog.csdn.net/xiao_ma_nong_last/article/details/105672462