私はJavaでかなりの基本的な再帰問題を練習しています。文字列中の 'x'文字の数 - 再帰
public int countX(String str) {
if (str == null || str.length() == 0)
return 0;
else if (str.length() == 1)
return str.charAt(0) == 'x' ? 1 :0;
else {
return (str.charAt(str.length()-1) == 'x' ? 1 : 0) + countX(str.substring(0,str.length()-1));
}
}
これは正常に動作します -
countX("xxhixx") → 4
countX("xhixhix") → 3
countX("hi") → 0
"という文字列を考えると、文字列内の小文字の 'はx' の文字の数を再帰的に(何のループ)を計算していません"。しかし、私はそれを書く良い方法があるかどうかを知りたいです。私はこのコードが単純な問題のために複雑であることを知っています。
、なぜあなたは ''回数= 1 'オーバー 'カウント++選んだのですか? –
@MadPhysicistスタイルだけです。変わりはない :) –