C♯の勉強

C♯4.0 で TopCoder の過去問を解きます。

TopCoder SRM593: WolfDelaymaster

最初の 'w' の個数を数えて、それに対応する wolf 文字列でちゃんと始まっているかチェックしていけばよい。
"w..w"+"o..o"+"l..l"+"f..f"の文字列生成はSelectManyで。

public class WolfDelaymaster {
    public string check(string str) {
        if (str == "") return "VALID";
        int w = str.TakeWhile(c => c == 'w').Count();
        if (w == 0) return "INVALID";
        string wolf = new String("wolf".SelectMany(c => Enumerable.Repeat(c, w)).ToArray());
        if (str.StartsWith(wolf)) return check(str.Substring(wolf.Length));
        return "INVALID";
    }
}