char array
再帰を使用して文字列 (つまり) 処理を行っています。私のrecursion tree
では、にある文字列のchild
長さは 1 未満parent
であり、同じ高さのすべての子は同じ長さの文字列ですが、文字が異なります。string
新しい長さが古い文字列の長さ以上になるたびに再帰を停止したいのですが、再帰の間にこの条件を挿入できません。を使用するSystem.exit(0)
と、完全なプログラムが終了しますが、これは望ましくありません。以下は私のコードスニペットです-
private static void getMinLen(char[] oldStr) {
int len = oldStr.length;
/*
* This terminates the whole program, using break in place of
* System.exit(0) is not effective
*/
if (len < 2)
System.exit(0);
char[] newStr = new char[len - 1];
for (int i = 0; i < len - 1; i++) {
/*
* Every character is matched with its next character and a new char
* array is created having length (len-1)
*/
getMinLen(newStr);
}
}
System.out.println("length=" + len);
実際に3行目に入れたとき。最初は長さを降順で出力しますが、再帰により長さが増加し、減少します。つまり、コンソールには次のように表示されます-
length=6
length=5
length=4
length=3
length=2
length=1
length=3
length=3
length=2
length=1
length=4
length=3
length=2
length=1
新しい長さが古い長さ以上になるたびに、再帰を停止したいだけです。