牛客每日一題4.2 月月查華華的手機 二分查找

問題就是詢問某一個串是不是初始串的子序列。
那麼序列都是小寫字母,就對存入每一個字母在初始串的位置。然後對目標串的字母一個個查詢,如果存在一個最接近並且比上一個字母遠的位置,則這個當前字母是存在序列中的,不斷的遍歷完整個目標串就可以了。開個vector,upper_bound真香

char node[max_],temp[max_];
vector<int> ind[30];
signed main() {
//	scanf_s("%s", node + 1);
	cin >> node + 1;
	int len = strlen(node + 1);
	for (int i = 1; i <= len; i++) {
		ind[node[i] - 'a'].push_back(i);
	}
	int T; cin >> T;
	while (T--){
		cin >> temp + 1;
		int len = strlen(temp + 1);
		int flag = 1,now = 0;
		for (int i = 1; i <= len; i++) {
			int wei = upper_bound(ind[temp[i] - 'a'].begin(), ind[temp[i] - 'a'].end(), now) - ind[temp[i] - 'a'].begin();
			if (wei >= ind[temp[i] - 'a'].size()) {
				flag = 0; break;
			}
			now = ind[temp[i] - 'a'][wei];
		}
		if (flag) {
			cout << "Yes\n";
		}
		else {
			cout << "No\n";
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章