日々精進

新しく学んだことを書き留めていきます

SRM489 Div2 Easy

問題の分析
与えられた文字列の配列から、与えられた各文字列prefix(前方一致), suffix(後方一致), substring(部分一致)にマッチする文字列の数を求めなさい。
方針
前方一致、後方一致はStartsWith, EndsWithメソッドを使えば判定できます。
部分一致だけc#の言語仕様とマッチさせたい場合がことなるので注意が必要です。
c#のIndexOfメソッドを使って部分一致しているかどうかを判定する場合、IndexOfは前方一致、後方一致の場合も一致している場所のインデックスを返すので
最初と最後の文字を削ってからIndexOfでマッチングさせてやる必要があります。
ソースコード

using System;
using System.Collections.Generic;
using System.Text;
 
 
public class BadVocabulary
{
    public int count(string badPrefix, string badSuffix, string badSubstring, string[] vocabulary)
    {
        int cnt = 0;
        foreach (string word in vocabulary)
        {
            int idx = 0;
            if (word.Length <= 2)
                idx = -1;
            else
                idx = word.Substring(1, word.Length - 2).IndexOf(badSubstring);
            if (word.StartsWith(badPrefix) || word.EndsWith(badSuffix) || idx != -1)
                cnt++;
        }
        return cnt;
    }
}