C♯の勉強

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

TopCoder SRM611: InterestingNumber

xの中に '0' から '9'の文字について

  • 0個か2個しか含まれてない
  • 2個ある場合は、その間にある文字数とその文字が表す数字が等しい。

かどうかをチェックする。

public class InterestingNumber {
    public string isInteresting(string x) {
        for (int i = 0; i < 10; i++) {
            char ch = (char)(i + '0');
            int count = x.Count(c => c == ch);
            if (count == 0) continue;
            if (count == 2) {
                var pos1 = x.IndexOf(ch);
                var pos2 = x.LastIndexOf(ch);
                if (pos2 - pos1 != i + 1)
                    return "Not interesting";
            } else {
                return "Not interesting";
            }
        }
        return "Interesting";
    }
}