このTopCoderの問題はこちらで見ることができる(要TopCoder登録 & 問題文は英語)。それでは、問題について説明する。
プレーヤーを表すAとBという文字がある。A、Bが実行したことをA、Bという文字列で表したmovesという文字列が与えられたときに、AかBの最大コンボ数を返すメソッドを作成せよ。コンボというのは相手に邪魔されていない一連の実行を指す。
例えばAABAAABBBBAとあれば、Bの4連続が最大で続いた回数になるので4が回答になる。
私の解答はこちら。
public class ComboLength {
public int howLong(String moves) {
String[] sp = moves.split("");
String start = sp[0];
int max = 1;
int combo = 1;
for( int i=1 ; i<sp.length ; i++ ){
if( start.equals(sp[i]) ){
combo++;
max = Math.max(max, combo);
}else{
combo = 1;
start = sp[i];
}
}
return max;
}
}得点は244.71/250。上位者の回答でお気に入りはこれ。分岐もStringオブジェクトの大量生成もなく、スマートに感じました。
public class ComboLength {
public int howLong(String moves) {
char prev = -1;
int result = 0;
int count = 1;
for( final char c : moves.toCharArray() ){
count = (c == prev) ? count+1 : 1;
result = Math.max(result, count);
prev = c;
}
return result;
}
}
0 件のコメント:
コメントを投稿