给定三个字符串S , S1 ,和S2 ,任务是检查以S1和S2开头和结尾的子字符串的数量是否等于以S2和S1开头和结尾的子字符串的数量。如果发现是真的,则打印“是” 。否则,打印“否” 。
例子:
Input: S = “helloworldworldhelloworld”, S1 = “hello”, S2 = “world”
Output: No
Explanation:
The substrings that starts with S1 (= “hello”) and ends with S2 (= “world”) are {“helloworld”, “helloworldworld”, “helloworldworldhelloworld”, “helloworld”}.
Therefore, the total count is 4.
The substrings that starts with S2 (= “world”) and ends with S1(= “hello”) are {“worldworldhello”, “worldhello”}.
Therefore, the total count is 2.
Therefore, the above two counts are not the same.
Input: S = “opencloseopencloseopen”, S1 = “open”, S2 = “close”
Output: Yes
方法:请按照以下步骤解决问题:
- 存储字符串S , S1的长度,和S2在变量中,例如N , N1 ,和N2分别。
- 初始化一个变量,例如count ,以在字符串S中存储子字符串S1的出现次数。
- 初始化一个变量,例如ans ,以存储分别以S1和S2开头和结尾的子字符串。
- 遍历给定的字符串S并执行以下步骤:
- 将字符串S的子字符串从大小为N1的索引i开始存储在字符串prefix中。
- 将字符串S的子字符串从大小为N2的索引i开始存储在字符串后缀中。
- 如果前缀与字符串S1相同,则将count的值增加1 。
- 如果后缀与字符串S2相同,则将ans的值增加count 。
- 使用以上步骤,查找分别以S2和S1开头和结尾的子字符串数。将获得的计数存储在变量ans2中。
- 如果发现ans和ans2的值相等,则打印“是” 。否则,打印“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count number of
// substrings that starts with
// string S1 and ends with string S2
int countSubstrings(string S, string S1,
string S2)
{
// Stores the length of each string
int N = S.length();
int N1 = S1.length();
int N2 = S2.length();
// Stores the count of prefixes
// as S1 and suffixes as S2
int count = 0, totalcount = 0;
// Traverse string S
for (int i = 0; i < N; i++) {
// Find the prefix at index i
string prefix = S.substr(i, N1);
// Find the suffix at index i
string suffix = S.substr(i, N2);
// If the prefix is S1
if (S1 == prefix)
count++;
// If the suffix is S2
if (S2 == suffix)
totalcount += count;
}
// Return the count of substrings
return totalcount;
}
// Function to check if the number of
// substrings starts with S1 and ends
// with S2 and vice-versa is same or not
void checkSubstrings(string S, string S1,
string S2)
{
// Count the number of substrings
int x = countSubstrings(S, S1, S2);
int y = countSubstrings(S, S2, S1);
// Print the result
if (x == y)
cout << "Yes";
else
cout << "No";
}
// Driver Code
int main()
{
string S = "opencloseopencloseopen";
string S1 = "open";
string S2 = "close";
checkSubstrings(S, S1, S2);
return 0;
}
时间复杂度: O(N *(N1 + N2)),其中N,N1和N2分别是字符串S,S1和S2的长度。
辅助空间: O(1)