Java程序最小化要更改的字符以使字符串的左右旋转相同
给定一个由小写英文字母组成的字符串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.
方法:解决问题的关键观察是当字符串的长度是偶数时,那么偶数索引处的所有字符和奇数索引处的字符必须相同,左右旋转相同。对于奇数长度的字符串,所有字符必须相等。请按照以下步骤解决问题:
- 检查字符串的长度是否为偶数,则要更改的最小字符数是字符串的长度,不包括偶数索引和奇数索引处出现次数最多的元素的频率。
- 否则,如果字符串的长度是奇数,则要更改的最小字符数是字符串的长度,不包括字符串中出现频率最高的字符。
- 打印获得的最终计数。
下面是上述方法的实现:
Java
// Java program of the
// above approach
class GFG{
// Function to find the minimum
// characters to be removed from
// the string
public static 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
int[] freqEven = new int[128];
int[] freqOdd = new int[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.charAt(i)]++;
}
else
{
freqOdd[str.charAt(i)]++;
}
}
// Stores the most occurring frequency
// for even and odd indices
int evenMax = 0, oddMax = 0;
for(char chr = 'a'; chr <= 'z'; chr++)
{
evenMax = Math.max(evenMax,
freqEven[chr]);
oddMax = Math.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
int[] freq = new int[128];
for(int i = 0; i < n; i++)
{
freq[str.charAt(i)]++;
}
// Stores the most occurring character
// in the string
int strMax = 0;
for(char chr = 'a'; chr <= 'z'; chr++)
{
strMax = Math.max(strMax, freq[chr]);
}
// Update the answer
ans = ans - strMax;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksgeeks";
System.out.print(getMinimumRemoval(str));
}
}
// This code is contributed by divyeshrabadiya07
6
时间复杂度: O(N)
辅助空间: O(1)
请参阅完整文章最小化要更改的字符以使字符串的左右旋转相同以获取更多详细信息!