📌  相关文章
📜  最小字符串使得给定字符串的每个相邻字符仍然相邻

📅  最后修改于: 2021-09-05 08:52:00             🧑  作者: Mango

给定一个字符串S,任务是找到的最小长度字符串,该字符串中相邻字符保持在最小长度的字符串相邻。

例子:

方法:思想是准备一个类似图的结构,其中图的每个相邻节点表示字符串的相邻字符。在两种情况下,这种类型的字符串是不可能的——

  • 如果一个字符包含三个或更多相邻字符。
  • 如果两个字符不只有一个相邻字符,长度为 1 的字符串除外。

如果字符串的上述条件为真,则只需使用深度优先搜索遍历遍历图形,此遍历的路径将是最小长度的字符串。为DFS源顶点将是字符仅具有一个相邻的字符的任何一个。

下面是上述方法的实现:

C++
// C++ implementation to find the
// minimum length string such that
// adjacent characters of the string
// remains adjacent in the string
 
#include 
using namespace std;
 
class graph {
    int arr[26][2];
    vector alpha;
    vector answer;
 
public:
    // Constructor for the graph
    graph()
    {
        // Initialize the matrix by -1
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < 2; j++)
                arr[i][j] = -1;
        }
 
        // Initialize the alphabet array
        alpha = vector(26);
    }
 
    // Function to do Depth first
    // search Traversal
    void dfs(int v)
    {
        // Pushing current character
        answer.push_back(v);
 
        alpha[v] = 1;
 
        for (int i = 0; i < 2; i++) {
            if (alpha[arr[v][i]] == 1
                || arr[v][i] == -1)
                continue;
 
            dfs(arr[v][i]);
        }
    }
 
    // Function to find the minimum
    // length string
    void minString(string str)
    {
        // Condition if given string
        // length is 1
        if (str.length() == 1) {
            cout << str << "\n";
            return;
        }
 
        bool flag = true;
 
        // Loop to find the adjacency
        // list of the given string
        for (int i = 0; i < str.length() - 1;
             i++) {
            int j = str[i] - 'a';
            int k = str[i + 1] - 'a';
 
            // Condition if character
            // already present
            if (arr[j][0] == k
                || arr[j][1] == k) {
            }
            else if (arr[j][0] == -1)
                arr[j][0] = k;
            else if (arr[j][1] == -1)
                arr[j][1] = k;
 
            // Condition if a character
            // have more than two different
            // adjacent characters
            else {
                flag = false;
                break;
            }
 
            if (arr[k][0] == j
                || arr[k][1] == j) {
            }
            else if (arr[k][0] == -1)
                arr[k][0] = j;
            else if (arr[k][1] == -1)
                arr[k][1] = j;
 
            // Condition if a character
            // have more than two different
            // adjacent characters
            else {
                flag = false;
                break;
            }
        }
 
        // Variable to check string contain
        // two end characters or not
        bool contain_ends = false;
 
        int count = 0;
        int index;
 
        for (int i = 0; i < 26; i++) {
 
            // Condition if a character has
            // only one type of adjacent
            // character
            if ((arr[i][0] == -1
                 && arr[i][1] != -1)
                || (arr[i][1] == -1
                    && arr[i][0] != -1)) {
                count++;
                index = i;
            }
 
            // Condition if the given string
            // has exactly two characters
            // having only one type of adjacent
            // character
            if (count == 2)
                contain_ends = true;
 
            if (count == 3)
                contain_ends = false;
        }
 
        if (contain_ends == false
            || flag == false) {
            cout << "Impossible"
                 << "\n";
            return;
        }
 
        // Depth first Search Traversal
        // on one of the possible end
        // character of the string
        dfs(index);
 
        // Loop to print the answer
        for (int i = 0; i < answer.size();
             i++) {
            char ch = answer[i] + 'a';
            cout << ch;
        }
    }
};
 
// Driver Code
int main()
{
    string s = "acabpba";
 
    graph g;
    g.minString(s);
 
    return 0;
}


Java
// Java implementation to find the
// minimum length string such that
// adjacent characters of the string
// remains adjacent in the string
import java.util.ArrayList;
 
class Graph{
     
int[][] arr;
ArrayList alpha;
ArrayList answer;
 
// Constructor for the Graph
public Graph()
{
    arr = new int[26][2];
     
    // Initialize the matrix by -1
    for(int i = 0; i < 26; i++)
    {
        for(int j = 0; j < 2; j++)
            arr[i][j] = -1;
    }
 
    // Initialize the alphabet array
    alpha = new ArrayList<>();
    for(int i = 0; i < 26; i++)
    {
        alpha.add(0);
    }
 
    answer = new ArrayList<>();
}
 
// Function to do Depth first
// search Traversal
void dfs(int v)
{
     
    // Pushing current character
    answer.add(v);
 
    alpha.set(v, 1);
 
    for(int i = 0; i < 2; i++)
    {
        if (arr[v][i] == -1 ||
            alpha.get(arr[v][i]) == 1)
            continue;
 
        dfs(arr[v][i]);
    }
}
 
// Function to find the minimum
// length string
void minString(String str)
{
     
    // Condition if given string
    // length is 1
    if (str.length() == 1)
    {
        System.out.println(str);
        return;
    }
 
    boolean flag = true;
 
    // Loop to find the adjacency
    // list of the given string
    for(int i = 0; i < str.length() - 1; i++)
    {
        int j = str.charAt(i) - 'a';
        int k = str.charAt(i + 1) - 'a';
 
        // Condition if character
        // already present
        if (arr[j][0] == k || arr[j][1] == k)
        {}
        else if (arr[j][0] == -1)
            arr[j][0] = k;
        else if (arr[j][1] == -1)
            arr[j][1] = k;
 
        // Condition if a character
        // have more than two different
        // adjacent characters
        else
        {
            flag = false;
            break;
        }
 
        if (arr[k][0] == j || arr[k][1] == j)
        {}
        else if (arr[k][0] == -1)
            arr[k][0] = j;
        else if (arr[k][1] == -1)
            arr[k][1] = j;
 
        // Condition if a character
        // have more than two different
        // adjacent characters
        else
        {
            flag = false;
            break;
        }
    }
 
    // Variable to check string contain
    // two end characters or not
    boolean contain_ends = false;
 
    int count = 0;
    int index = 0;
 
    for(int i = 0; i < 26; i++)
    {
         
        // Condition if a character has
        // only one type of adjacent
        // character
        if ((arr[i][0] == -1 && arr[i][1] != -1) ||
            (arr[i][1] == -1 && arr[i][0] != -1))
        {
            count++;
            index = i;
        }
 
        // Condition if the given string
        // has exactly two characters
        // having only one type of adjacent
        // character
        if (count == 2)
            contain_ends = true;
 
        if (count == 3)
            contain_ends = false;
    }
 
    if (contain_ends == false || flag == false)
    {
        System.out.println("Impossible");
        return;
    }
 
    // Depth first Search Traversal
    // on one of the possible end
    // character of the string
    dfs(index);
 
    // Loop to print the answer
    for(int i = 0; i < answer.size(); i++)
    {
        char ch = (char)(answer.get(i) + 'a');
        System.out.print(ch);
    }
}
}
 
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    String s = "acabpba";
 
    Graph graph = new Graph();
    graph.minString(s);
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python implementation to find the
# minimum length string such that
# adjacent characters of the string
# remains adjacent in the string
 
# Initialize the matrix by -1
arr = [[-1 for i in range(2)] for j in range(26)]
 
# Initialize the alphabet array
alpha = [0 for i in range(26)]
answer = []
 
# Function to do Depth first
# search Traversal
def dfs(v):
    global arr
    global alpha
    global answer
 
    # Pushing current character
    answer.append(v)
    alpha[v] = 1
 
    for i in range(2):
        if(alpha[arr[v][i]] == 1 or arr[v][i] == -1):
            continue
        dfs(arr[v][i])
 
# Function to find the minimum
# length string
def minString(Str):
   
    # Condition if given string
    # length is 1
    if(len(Str) == 1):
        print(Str)
        return
 
    flag = True
    temp = 0
     
    # Loop to find the adjacency
    # list of the given string
    for i in range(0,len(Str) - 1):
        j = ord(Str[i]) - ord('a')
 
        k = ord(Str[i + 1]) - ord('a')
 
        # Condition if character
        # already present we can do nothing
        if(arr[j][0] == k or arr[j][1] == k):
            temp = 1
 
        elif(arr[j][0] == -1):
            arr[j][0] = k
        elif(arr[j][1] == -1):
            arr[j][1] = k
             
        # Condition if a character
        # have more than two different
        # adjacent characters
        else:
            flag = alse
            break
 
        if(arr[k][0] == j or arr[k][1] == j):
            temp = 0
        elif(arr[k][0] == -1):
            arr[k][0] = j
        elif(arr[k][1] == -1):
            arr[k][1] = j
         
        # Condition if a character
        # have more than two different
        # adjacent characters
        else:
            flag = False
            break
 
    # Variable to check string contain
    # two end characters or not
    contain_ends = False
 
    count = 0
    index = 0
 
    for i in range(26):
       
        # Condition if a character has
        # only one type of adjacent
        # character
        if((arr[i][0] == -1 and arr[i][1] != -1) or (arr[i][1] == -1 and arr[i][0] != -1)):
            count += 1
            index = i
 
        # Condition if the given string
        # has exactly two characters
        # having only one type of adjacent
        # character
        if(count == 2):
            contain_ends = True
        if(count == 3):
            contain_ends = False
 
    if(contain_ends == False or flag == False):
        print("Impossible")
        return
 
    # Depth first Search Traversal
    # on one of the possible end
    # character of the string
    dfs(index)
 
    # Loop to print the answer
    for i in range(len(answer)):
        ch = chr(answer[i] + ord('a'))
        print(ch, end = "")
 
# Driver Code
s = "acabpba"
minString(s)
 
# This code is contributed by avanitrachhadiya2155


输出:
pbac

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live