C語言程式查詢給定字串的排列


假設我們在一個數組中有一些字串。我們必須找到它們在不同行中的所有排列。

因此,如果輸入類似於 strings = ["abc", "def", "ghi"],則輸出將為

abc def ghi
abc ghi def
def abc ghi
def ghi abc
ghi abc def
ghi def abc

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個函式 next_permutation(),它將接收 n 和字串陣列 s 作為引數。
  • 從 i := n - 1 開始,當 i > 0 時,更新(i 減 1),執行以下操作:
    • 如果 s[i] > s[i - 1],則
      • j := i + 1
    • 從 j < n 開始,更新(j 加 1),執行以下操作:
      • 如果 s[j] <= s[i - 1],則
        • 退出迴圈
      • t := s[i - 1]
    • s[i - 1] = s[j - 1]
    • s[j - 1] = t
    • 從 i < n - 1 開始,更新(i 加 1),(n 減 1),執行以下操作:
      • t := s[i]
      • s[i] := s[n - 1]
      • s[n - 1] = t
    • 返回 1
  • 從 i := 0 開始,當 i < n - 1 時,更新(i 加 1),(n 減 1),執行以下操作:
    • t := s[i]
    • s[i] := s[n - 1]
    • s[n - 1] = t
  • 返回 0
  • 從主方法執行以下操作
  • 無限迴圈執行以下操作,直到 next_permutation(n, strings) 為 0:
    • 從 i := 0 開始,當 i < n 時,更新(i 加 1),執行以下操作:
      • 顯示 strings[i],然後(如果 i 等於 n - 1,則換行,否則列印空格)

示例

讓我們看看以下實現以獲得更好的理解:

#include <stdio.h>
#include <string.h>
int next_permutation(int n, char **s){
    for (int i = n - 1; i > 0; i--)
        if (strcmp(s[i], s[i - 1]) > 0){
            int j = i + 1;
            for (; j < n; j++)
                if (strcmp(s[j], s[i - 1]) <= 0)
                    break;
            char *t = s[i - 1];
            s[i - 1] = s[j - 1];
            s[j - 1] = t;
            for (; i < n - 1; i++, n--){
                t = s[i];
                s[i] = s[n - 1];
                s[n - 1] = t;
            }
            return 1;
        }
    for (int i = 0; i < n - 1; i++, n--){
        char *t = s[i];
        s[i] = s[n - 1];
        s[n - 1] = t;
    }
    return 0;
}
int main(){
    char *strings[] = {"abc", "def", "ghi"};
    int n = 3;
    do{
        for (int i = 0; i < n; i++)
            printf("%s%c", strings[i], i == n - 1 ? '
' : ' ');     } while (next_permutation(n, strings)); }

輸入

{"abc", "def", "ghi"}

輸出

abc def ghi
abc ghi def
def abc ghi
def ghi abc
ghi abc def
ghi def abc

更新於: 2021年10月8日

5K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.