簡體   English   中英

如何通過每次刪除4個字符來獲取字符串的所有組合?

[英]How to get all combinations of a string by removing 4 characters each time?

我正在嘗試在JavaScript中創建一個函數,該函數對於給定的字符串將通過每次僅從字符串中刪除4個字符來輸出所有可能的組合。 我如何輸出所有組合?起始字符串的長度是動態的。

**注意:**刪除4個字符的順序不應該總是連續的

例:

string:BmamdWRtaW51dGfVzZMI=  //B   m   a   m  d  W   R  t  a  W   5   1   d   G   f  V  z  Z  M  I  =
                             // 1   2   3   4  5  6   7  8  9  10  11  12  13  14  15 16 17 18 19 20 21

要打印所有可能的組合,如下所示:

 BmamdWRtaW51dGfVzZMI= (starting string)
-dWRtaW51dGfVzZMI=     (removed first 4 characters)
-BWRtaW51dGfVzZMI=     (removed 4 consecutive charaters start from 2th character)
-BmRtaW51dGfVzZMI=     (removed 4 consecutive charaters start from 3th character)
-BmataW51dGfVzZMI=     (removed 4 consecutive charaters start from 4th character)
-
-

假設字符串的長度為str

for (a=0; a<n-3; a++) {
    for (b=a+1; b<n-2; b++) {
        for (c=b+1; c<n-1; c++) {
            for (d=c+1; d<n; d++) {
                //delete the ath, bth, cth and dth charaters of the initial string
                result = str.substr(0, a)+str.substr(a+1, b-a-1)+str.substr(b+1, c-b-1)+str.substr(c+1, d-c-1)+str.substr(d+1);

                //and print the result
            }
        }
    }
}

遞歸函數的一些偽代碼:

myFunction (charactersRemoved, remainingString, previousString):

if charactersRemoved === 4 then echo previousString + remainingString
return

foreach character in remainingString
remainingString -= character
myFunction (charactersRemoved + 1, remainingString, previousString)
previousString += character
endfor

endfunction

myFunction(0, string, '')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM