C++程式中查詢以給定字串開頭和結尾的不同子字串
在本教程中,我們將編寫一個程式,查詢以給定字串開頭和結尾的子字串的總數。
給定一個字串和兩個子字串。我們需要找到以給定的兩個子字串開頭和結尾的不同子字串的數量。讓我們來看一個例子。
輸入
str = "getmesomecoffee" start = "m" end = "e"
輸出
6
給定字串中共有6個不同的子字串。它們是 **me, mesome, mesomemecoffe, mesomemecoffee, mecoffe, mecoffee。**
讓我們看看解決問題的步驟。
初始化字串。
遍歷字串並找到開頭和結尾子字串的索引。將它們儲存在單獨的陣列中。
初始化一個集合來儲存不同的子字串。
遍歷字串。
檢查當前索引是否與我們之前形成的陣列的起始字串匹配。
如果我們找到起始字串的索引,則搜尋結束字串。
將所有字串新增到一個變數中,直到我們找到結尾。
當我們找到結束字串時,遞增子字串計數並將子字串新增到集合中。
重置子字串變數。
列印子字串計數。
示例
讓我們看看程式碼。
#include <bits/stdc++.h>
using namespace std;
int getSubstringsCount(string str, string start, string end) {
int substrings_count = 0, str_length = str.size(), start_length = start.size(), end_length = end.size();
int start_matches_index[str_length] = {0}, end_matches_index[str_length] = {0};
for (int i = 0; i < str_length; i++) {
if (str.substr(i, start_length) == start) {
start_matches_index[i] = 1;
}
if (str.substr(i, end_length) == end) {
end_matches_index[i] = 1;
}
}
set<string> substrings;
string current_substring = "";
for (int i = 0; i < str_length; i++) {
if (start_matches_index[i]) {
for (int j = i; j < str_length; j++) {
if (!end_matches_index[j]) {
current_substring += str[j];
}
if (end_matches_index[j]) {
current_substring += str.substr(j, end_length);
if (substrings.find(current_substring) == substrings.end()) {
substrings_count++;
}
substrings.insert(current_substring);
}
}
current_substring = "";
}
}
return substrings_count;
}
int main() {
string str = "getmesomecoffee";
string start = "m";
string end = "e";
cout << getSubstringsCount(str, start, end) << endl;
return 0;
}輸出
如果執行上述程式,則會得到以下結果。
6
結論
如果您在本教程中有任何疑問,請在評論部分提出。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP