ねむーの日記~AtCoderな日々~

福岡に住むプログラミング好きのブログです!

【プログラミングコンテスト】AtCoder Beginner Contest 122②

来年から研究室に着任する助教の先生と仲良くなりました、ねむーです。

今回はAtCoder(https://atcoder.jp/contests/abc122)にて開催されました、AtCoder Beginner Contest 122のB問題「B - ATCoder」の問題と僕との戦闘記です。

0.はじめに

今回も、プログラミング言語C#を使用しています。

1.問題文

英大文字からなる文字列 S が与えられます。 S の部分文字列 (注記を参照) であるような最も長い ACGT 文字列 の長さを求めてください。

ここで、ACGT 文字列とは A, C, G, T 以外の文字を含まない文字列です。

2.入力例

  • 入力
HATAGAYA
  • 出力
5

3.初見の感想

  • 左から走査してATGC連続数の最大を調べる
  • 文字列をcharに分割

4.コードの簡単な解説

  • まず、入力の値のパースを行う
        char[] input = Console.ReadLine().ToArray();
  • 左から走査してATGC連続数を調べる、最大ならば更新
        int max = 0;
        int temp = 0;
        for(int i = 0; i < input.Length; i++)
        {
            if(input[i]=='A'|| input[i] == 'G'|| input[i] == 'T'|| input[i] == 'C')
            {
                temp++;
            }
            else
            {
                if (max < temp) { max = temp; }
                temp = 0;
            }
        }
  • 一回もATGCじゃない文字が出なかった時の例外処理
        if (max < temp) { max = temp; }
  • 描画
        Console.WriteLine(max);

5.全コード

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        char[] input = Console.ReadLine().ToArray();
        int max = 0;
        int temp = 0;
        for(int i = 0; i < input.Length; i++)
        {
            if(input[i]=='A'|| input[i] == 'G'|| input[i] == 'T'|| input[i] == 'C')
            {
                temp++;
            }
            else
            {
                if (max < temp) { max = temp; }
                temp = 0;
            }
        }
        if (max < temp) { max = temp; }
        Console.WriteLine(max);
    }
}

6.最後に

例外処理に気付けたのがよかったです(^^)