C++程序最小化要更改的字符以使字符串的左右旋转相同
给定一个由小写英文字母组成的字符串S ,任务是找到要更改的最小字符数,以使字符串的左右旋转相同。
例子:
Input: S = “abcd”
Output: 2
Explanation:
String after the left shift: “bcda”
String after the right shift: “dabc”
Changing the character at position 3 to ‘a’ and character at position 4 to ‘b’, the string is modified to “abab”.
Therefore, both the left and right rotations becomes “baba”.
Input: S = “gfg”
Output: 1
Explanation:
After updating the character at position 1 to ‘g’, the string becomes “ggg”.
Therefore, the left and right rotation are equal.
方法:解决问题的关键观察是当字符串的长度是偶数时,那么偶数索引处的所有字符和奇数索引处的字符必须相同,左右旋转相同。对于奇数长度的字符串,所有字符必须相等。请按照以下步骤解决问题:
- 检查字符串的长度是否为偶数,则要更改的最小字符数是字符串的长度,不包括偶数索引和奇数索引处出现次数最多的元素的频率。
- 否则,如果字符串的长度是奇数,则要更改的最小字符数是字符串的长度,不包括字符串中出现频率最高的字符。
- 打印获得的最终计数。
下面是上述方法的实现:
C++
// C++ Program of the
// above approach
#include
using namespace std;
// Function to find the minimum
// characters to be removed from
// the string
int getMinimumRemoval(string str)
{
int n = str.length();
// Initialize answer by N
int ans = n;
// If length is even
if (n % 2 == 0) {
// Frequency array for odd
// and even indices
vector freqEven(128);
vector freqOdd(128);
// Store the frequency of the
// characters at even and odd
// indices
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
freqEven[str[i]]++;
}
else {
freqOdd[str[i]]++;
}
}
// Stores the most occuring frequency
// for even and odd indices
int evenMax = 0, oddMax = 0;
for (char chr = 'a'; chr <= 'z'; chr++) {
evenMax = max(evenMax, freqEven[chr]);
oddMax = max(oddMax, freqOdd[chr]);
}
// Update the answer
ans = ans - evenMax - oddMax;
}
// If length is odd
else {
// Stores the frequency of the
// characters of the string
vector freq(128);
for (int i = 0; i < n; i++) {
freq[str[i]]++;
}
// Stores the most occuring character
// in the string
int strMax = 0;
for (char chr = 'a'; chr <= 'z'; chr++) {
strMax = max(strMax, freq[chr]);
}
// Update the answer
ans = ans - strMax;
}
return ans;
}
// Driver Code
int main()
{
string str = "geeksgeeks";
cout << getMinimumRemoval(str);
}
6
时间复杂度: O(N)
辅助空间: O(1)
请参阅完整文章最小化要更改的字符以使字符串的左右旋转相同以获取更多详细信息!