在 C++ 中使用 ArrayList 列印字串的所有子序列


本問題為我們提供一個字串,目的是列印字串的所有子序列。子串是透過刪除元素形成的。另外,字串的順序不可更改。

下面透過一個示例,以便更好地理解問題 −

Input: string = “xyz”
Output: x y xy z xz yz xyz

為了解決這個問題,我們將找到從凍結字串第一個字元開始的所有子串,並相應地找到子序列,然後尋找字串中的下一個字元和子序列。

示例

public class Main {
   public static void printSubString(String sub,String subSeq){
      if (sub.length() == 0) {
         System.out.print(subSeq+" ");
         return;
      }
      char ch = sub.charAt(0);
      String ros = sub.substring(1);
      printSubString(ros, subSeq);
      printSubString(ros, subSeq + ch);
   }
   public static void main(String[] args){
      String str = "wxyz";
      System.out.println("The subStrings are :");
      printSubString(str, "");
   }
}

輸出

子串為 −

z y yz x xz xy xyz w wz wy wyz wx wxz wxy wxyz

更新於: 17-Jan-2020

93 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.