📌  相关文章
📜  使用散列重新排列字符中的字符串,以便没有两个相邻的字符相同

📅  最后修改于: 2021-10-27 07:48:30             🧑  作者: Mango

给定一个字符串str用重复的字符,该任务是重新排列字符串中的,使得没有两个相邻的字符是相同的。如果可能,则打印Yes否则打印No
例子:

方法:思想是将每个字符的频率存储在一个unordered_map中,并将字符的最大频率与字符串长度和最大频率数的差异进行比较。如果最大频率小于差值,则可以安排否则不安排。

  1. 让我们开始交替放置所有具有最大频率的字符。那么至少,我们需要在它们之间使用 (max_freq-1) 个空格来解决问题,以便它们彼此不相邻。
  2. 但是我们还有(字符串的长度 – max_freq)个空格。因此,(字符串的长度 – max_freq)应该至少是 (max_freq-1) 以确保没有两个字符是相同的。
  3. 所以,它是这样的:(max_freq-1) <= (字符串的长度 – max_freq)

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
#include 
using namespace std;
 
// Function that returns true if it is possible
// to rearrange the characters of the string
// such that no two consecutive characters are same
int isPossible(string str)
{
 
    // To store the frequency of
    // each of the character
    unordered_map freq;
 
    // To store the maximum frequency so far
    int max_freq = 0;
    for (int j = 0; j < (str.length()); j++) {
        freq[str[j]]++;
        if (freq[str[j]] > max_freq)
            max_freq = freq[str[j]];
    }
 
    // If possible
    if (max_freq <= (str.length() - max_freq + 1))
        return true;
    return false;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
 
    if (isPossible(str))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG {
 
    // Function that returns true if it is possible
    // to rearrange the characters of the string
    // such that no two consecutive characters are same
    static boolean isPossible(char[] str)
    {
 
        // To store the frequency of
        // each of the character
        Map freq = new HashMap<>();
 
        // To store the maximum frequency so far
        int max_freq = 0;
        for (int j = 0; j < (str.length); j++) {
            if (freq.containsKey(str[j])) {
                freq.put(str[j], freq.get(str[j]) + 1);
                if (freq.get(str[j]) > max_freq)
                    max_freq = freq.get(str[j]);
            }
            else {
                freq.put(str[j], 1);
                if (freq.get(str[j]) > max_freq)
                    max_freq = freq.get(str[j]);
            }
        }
 
        // If possible
        if (max_freq <= (str.length - max_freq + 1))
            return true;
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
 
        if (isPossible(str.toCharArray()))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Function that returns true if it is possible
# to rearrange the characters of the String
# such that no two consecutive characters are same
def isPossible(Str):
 
    # To store the frequency of
    # each of the character
    freq = dict()
 
    # To store the maximum frequency so far
    max_freq = 0
    for j in range(len(Str)):
        freq[Str[j]] = freq.get(Str[j], 0) + 1
        if (freq[Str[j]] > max_freq):
            max_freq = freq[Str[j]]
 
    # If possible
    if (max_freq <= (len(Str) - max_freq + 1)):
        return True
    return False
 
# Driver code
Str = "geeksforgeeks"
 
if (isPossible(Str)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function that returns true if it is possible
    // to rearrange the characters of the string
    // such that no two consecutive characters are same
    static Boolean isPossible(char[] str)
    {
 
        // To store the frequency of
        // each of the character
        Dictionary freq = new Dictionary();
 
        // To store the maximum frequency so far
        int max_freq = 0;
        for (int j = 0; j < (str.Length); j++) {
            if (freq.ContainsKey(str[j])) {
                var v = freq[str[j]] + 1;
                freq.Remove(str[j]);
                freq.Add(str[j], v);
                if (freq[str[j]] > max_freq)
                    max_freq = freq[str[j]];
            }
            else {
                freq.Add(str[j], 1);
                if (freq[str[j]] > max_freq)
                    max_freq = freq[str[j]];
            }
        }
 
        // If possible
        if (max_freq <= (str.Length - max_freq + 1))
            return true;
        return false;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String str = "geeksforgeeks";
 
        if (isPossible(str.ToCharArray()))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by Princi Singh


Javascript


输出:
Yes

时间复杂度: O(N)
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程