📌  相关文章
📜  以排序字符串的字符重新排列,使得没有一对相邻的字符是相同的

📅  最后修改于: 2021-10-26 05:12:42             🧑  作者: Mango

给定的排序字符串S选自N小写字符,任务是给定的字符串,使得没有两个相邻的字符是相同的重新排列字符。如果无法按照给定的条件重新排列,则打印“-1”

例子:

方法:给定的问题可以通过使用两点技术来解决。请按照以下步骤解决此问题:

  • 遍历字符串S和检查的字符,如果没有两个相邻的字符字符串中的同一然后打印字符串S。
  • 否则,如果字符串的大小为2并且具有相同的字符,则打印“-1”
  • 初始化三个变量,例如, i0j1k2以遍历字符串S
  • k小于N 时迭代并执行以下步骤:
    • 如果S [i]不等于S [j]时,然后通过递增1 ij,以及增量K内1,如果j的值等于k。
    • 否则,如果S [j]的等于S [k]的,由1个增量ķ。
    • 否则,交换s[j]s[k]并将ij增加1 ,如果j等于k,则将k增加1
  • 完成上述步骤后,反转字符串S
  • 最后,遍历字符串S的字符并检查是否没有两个相邻的字符相同。如果发现为真,则打印字符串S 。否则,打印“-1”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if a string S
// contains pair of adjacent
// characters that are equal or not
bool isAdjChar(string& s)
{
    // Traverse the string S
    for (int i = 0; i < s.size() - 1; i++) {
 
        // If S[i] and S[i+1] are equal
        if (s[i] == s[i + 1])
            return true;
    }
 
    // Otherwise, return false
    return false;
}
 
// Function to rearrange characters
// of a string such that no pair of
// adjacent characters are the same
void rearrangeStringUtil(string& S, int N)
{
    // Initialize 3 variables
    int i = 0, j = 1, k = 2;
 
    // Iterate until k < N
    while (k < N) {
 
        // If S[i] is not equal
        // to S[j]
        if (S[i] != S[j]) {
 
            // Increment i and j by 1
            i++;
            j++;
 
            // If j equals k and increment
            // the value of K by 1
            if (j == k) {
                k++;
            }
        }
 
        // Else
        else {
 
            // If S[j] equals S[k]
            if (S[j] == S[k]) {
 
                // Increment k by 1
                k++;
            }
 
            // Else
            else {
 
                // Swap
                swap(S[k], S[j]);
 
                // Increment i and j
                // by 1
                i++;
                j++;
 
                // If j equals k
                if (j == k) {
 
                    // Increment k by 1
                    k++;
                }
            }
        }
    }
}
 
// Function to rearrange characters
// in a string so that no two
// adjacent characters are same
string rearrangeString(string& S, int N)
{
 
    // If string is already valid
    if (isAdjChar(S) == false) {
        return S;
    }
 
    // If size of the string is 2
    if (S.size() == 2)
        return "-1";
 
    // Function Call
    rearrangeStringUtil(S, N);
 
    // Reversing the string
    reverse(S.begin(), S.end());
 
    // Function Call
    rearrangeStringUtil(S, N);
 
    // If the string is valid
    if (isAdjChar(S) == false) {
        return S;
    }
 
    // Otherwise
    return "-1";
}
 
// Driver Code
int main()
{
    string S = "aaabc";
    int N = S.length();
    cout << rearrangeString(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
    static char []S = "aaabc".toCharArray();
   
// Function to check if a String S
// contains pair of adjacent
// characters that are equal or not
static boolean isAdjChar()
{
   
    // Traverse the String S
    for (int i = 0; i < S.length - 1; i++)
    {
 
        // If S[i] and S[i+1] are equal
        if (S[i] == S[i + 1])
            return true;
    }
 
    // Otherwise, return false
    return false;
}
 
// Function to rearrange characters
// of a String such that no pair of
// adjacent characters are the same
static void rearrangeStringUtil(int N)
{
   
    // Initialize 3 variables
    int i = 0, j = 1, k = 2;
 
    // Iterate until k < N
    while (k < N) {
 
        // If S[i] is not equal
        // to S[j]
        if (S[i] != S[j]) {
 
            // Increment i and j by 1
            i++;
            j++;
 
            // If j equals k and increment
            // the value of K by 1
            if (j == k) {
                k++;
            }
        }
 
        // Else
        else {
 
            // If S[j] equals S[k]
            if (S[j] == S[k]) {
 
                // Increment k by 1
                k++;
            }
 
            // Else
            else {
 
                // Swap
                swap(k,j);
 
                // Increment i and j
                // by 1
                i++;
                j++;
 
                // If j equals k
                if (j == k) {
 
                    // Increment k by 1
                    k++;
                }
            }
        }
    }
}
static void swap(int i, int j)
{
    char temp = S[i];
    S[i] = S[j];
    S[j] = temp; 
}
// Function to rearrange characters
// in a String so that no two
// adjacent characters are same
static String rearrangeString(int N)
{
 
    // If String is already valid
    if (isAdjChar() == false) {
        return String.valueOf(S);
    }
 
    // If size of the String is 2
    if (S.length == 2)
        return "-1";
 
    // Function Call
    rearrangeStringUtil(N);
 
    // Reversing the String
    reverse();
 
    // Function Call
    rearrangeStringUtil(N);
 
    // If the String is valid
    if (isAdjChar() == false) {
        return String.valueOf(S);
    }
 
    // Otherwise
    return "-1";
}
static void reverse() {
     
    int l, r = S.length - 1;
    for (l = 0; l < r; l++, r--) {
        char temp = S[l];
        S[l] = S[r];
        S[r] = temp;
    }
}
   
// Driver Code
public static void main(String[] args)
{
     
    int N = S.length;
    System.out.print(rearrangeString(N));
 
}
}
 
// This code is contributed by Princi Singh


Python3
# Python 3 program for the above approach
S = "aaabc"
 
# Function to check if a string S
# contains pair of adjacent
# characters that are equal or not
def isAdjChar(s):
   
    # Traverse the string S
    for i in range(len(s)-1):
       
        # If S[i] and S[i+1] are equal
        if (s[i] == s[i + 1]):
            return True
 
    # Otherwise, return false
    return False
 
# Function to rearrange characters
# of a string such that no pair of
# adjacent characters are the same
def rearrangeStringUtil(N):
    global S
    S = list(S)
    # Initialize 3 variables
    i = 0
    j = 1
    k = 2
 
    # Iterate until k < N
    while (k < N):
 
        # If S[i] is not equal
        # to S[j]
        if (S[i] != S[j]):
 
            # Increment i and j by 1
            i += 1
            j += 1
 
            # If j equals k and increment
            # the value of K by 1
            if (j == k):
                k += 1
 
        # Else
        else:
 
            # If S[j] equals S[k]
            if (S[j] == S[k]):
 
                # Increment k by 1
                k += 1
 
            # Else
            else:
 
                # Swap
                temp = S[k]
                S[k] = S[j]
                S[j] = temp
                # Increment i and j
                # by 1
                i += 1
                j += 1
 
                # If j equals k
                if (j == k):
 
                    # Increment k by 1
                    k += 1
    S = ''.join(S)
 
# Function to rearrange characters
# in a string so that no two
# adjacent characters are same
def rearrangeString(N):
    global S
     
    # If string is already valid
    if (isAdjChar(S) == False):
        return S
 
    # If size of the string is 2
    if (len(S) == 2):
        return "-1"
 
    # Function Call
    rearrangeStringUtil(N)
 
    # Reversing the string
    S = S[::-1]
     
    # Function Call
    rearrangeStringUtil(N)
 
    # If the string is valid
    if (isAdjChar(S) == False):
        return S
 
    # Otherwise
    return "-1"
 
# Driver Code
if __name__ == '__main__':
    N = len(S)
    print(rearrangeString(N))
     
    # This code is contributed by ipg2016107.


C#
// C# program for the above approach
using System;
 
public class GFG
{
    static char []S = "aaabc".ToCharArray();
   
// Function to check if a String S
// contains pair of adjacent
// characters that are equal or not
static bool isAdjChar()
{
   
    // Traverse the String S
    for (int i = 0; i < S.Length - 1; i++)
    {
 
        // If S[i] and S[i+1] are equal
        if (S[i] == S[i + 1])
            return true;
    }
 
    // Otherwise, return false
    return false;
}
 
// Function to rearrange characters
// of a String such that no pair of
// adjacent characters are the same
static void rearrangeStringUtil(int N)
{
   
    // Initialize 3 variables
    int i = 0, j = 1, k = 2;
 
    // Iterate until k < N
    while (k < N) {
 
        // If S[i] is not equal
        // to S[j]
        if (S[i] != S[j]) {
 
            // Increment i and j by 1
            i++;
            j++;
 
            // If j equals k and increment
            // the value of K by 1
            if (j == k) {
                k++;
            }
        }
 
        // Else
        else {
 
            // If S[j] equals S[k]
            if (S[j] == S[k]) {
 
                // Increment k by 1
                k++;
            }
 
            // Else
            else {
 
                // Swap
                swap(k,j);
 
                // Increment i and j
                // by 1
                i++;
                j++;
 
                // If j equals k
                if (j == k) {
 
                    // Increment k by 1
                    k++;
                }
            }
        }
    }
}
static void swap(int i, int j)
{
    char temp = S[i];
    S[i] = S[j];
    S[j] = temp; 
}
   
// Function to rearrange characters
// in a String so that no two
// adjacent characters are same
static String rearrangeString(int N)
{
 
    // If String is already valid
    if (isAdjChar() == false) {
        return String.Join("",S);
    }
 
    // If size of the String is 2
    if (S.Length == 2)
        return "-1";
 
    // Function Call
    rearrangeStringUtil(N);
 
    // Reversing the String
    reverse();
 
    // Function Call
    rearrangeStringUtil(N);
 
    // If the String is valid
    if (isAdjChar() == false) {
        return String.Join("",S);
    }
 
    // Otherwise
    return "-1";
}
static void reverse() {
     
    int l, r = S.Length - 1;
    for (l = 0; l < r; l++, r--) {
        char temp = S[l];
        S[l] = S[r];
        S[r] = temp;
    }
}
   
// Driver Code
public static void Main(String[] args)
{
     
    int N = S.Length;
    Console.Write(rearrangeString(N));
 
}
}
 
// This code is contributed by shikhasingrajput


输出:
acaba

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

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