📌  相关文章
📜  Java程序最小化要更改的字符以使字符串的左右旋转相同

📅  最后修改于: 2022-05-13 01:55:45.429000             🧑  作者: Mango

Java程序最小化要更改的字符以使字符串的左右旋转相同

给定一个由小写英文字母组成的字符串S ,任务是找到要更改的最小字符数,以使字符串的左右旋转相同。

例子:

方法:解决问题的关键观察是当字符串的长度是偶数时,那么偶数索引处的所有字符和奇数索引处的字符必须相同,左右旋转相同。对于奇数长度的字符串,所有字符必须相等。请按照以下步骤解决问题:

  • 检查字符串的长度是否为偶数,则要更改的最小字符数是字符串的长度,不包括偶数索引和奇数索引处出现次数最多的元素的频率。
  • 否则,如果字符串的长度是奇数,则要更改的最小字符数是字符串的长度,不包括字符串中出现频率最高的字符。
  • 打印获得的最终计数。

下面是上述方法的实现:

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)

请参阅完整文章最小化要更改的字符以使字符串的左右旋转相同以获取更多详细信息!