找到频率最高且仅包含 X 和 Y 的子串
给定一个长度为N的字符串S由 (0-9) 中的数字和两个数字组成,一个是偶数(比如X ),一个是奇数(比如Y ) ,任务是找到出现时间最长且仅包含 X 或 Y。
注意:如果两个子字符串具有相同的频率,则返回按字典顺序较小的那个。
例子:
Input: N = 5, S =”48947″, X = ‘4’, Y = ‘9’
Output: 4
Explanation: Sub-string “4” occurring maximum number of times in “48947”.
Input: N = 8, S = “22772777”, X = ‘2’, Y = ‘7’
Output: 7
朴素的方法:-解决问题的基本方法是检查不同长度的不同子串,仅由给定的偶数和奇数组成。
时间复杂度: O(N 2 )
辅助空间: O(N 2 )
有效方法:借助以下观察可以有效地解决问题:
Just check out the occurrence of given even and odd digit.
Print out the digit from given X and Y which one occurs maximum number of times.
If both occur same number of times the print lexicographically minimum one.
原因:我们只检查唯一偶数和奇数的出现而不是长度大于1的子串的出现的原因:
Considering string: “22772777”
In this example “227” and “22” are occurring 1 time each, “27” is occurring 2 times and similarly for other substrings. But the single digit substring “7” is occurring 5 times which is the maximum among all.
The reason is the substrings of any length formed by only the given X and Y contain them as single length substrings. So they obviously occurs more times than the other substrings.
That is why, checking for only the given odd and even number substring of length 1 is needed.
请按照以下步骤解决问题:
- 初始化两个计数变量以存储 X 和 Y 的计数。
- 遍历字符串并检查:
- 如果当前字符是偶数或奇数并增加它们各自的计数。
- 比较两个计数并返回具有更大计数的计数。
- 如果它们的计数相同,则返回按字典顺序排列的最小值。
以下是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to find substring
// which occur maximum number of times
char find(int N, string S, char even, char odd)
{
// Count1 for even and count2 for odd
// traversing the whole string
int count1 = 0;
int count2 = 0;
for (int i = 0; i < N; i++) {
// Checking if the character is
// equal to even
if (S[i] == even)
count1++;
// Checking if the character
// is equal to odd
else if (S[i] == odd)
count2++;
}
// If even occur maximum times
if (count1 > count2)
return even;
// If odd occur maximum times
else if (count2 > count1)
return odd;
// If both occur same times
// checking which one is
// lexicographically minimum
else {
if (even - '0' < odd - '0')
return even;
else
return odd;
}
}
// Driver Code
int main()
{
// Length of string
int N = 8;
// Even and odd number
char even = '2', odd = '7';
string S = "22772777";
// Output string
string ans;
// Calling function to find string
ans = find(N, S, even, odd);
// Printing output
cout << ans << endl;
return 0;
}
7
时间复杂度: O(N)
辅助空间: O(1)