๐Ÿ‘ฉ‍๐Ÿ’ปProgramming/Coding Test

[C#] [BOJ#1157] ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ - Matches

taesooya 2022. 7. 30.

https://www.acmicpc.net/problem/1152

 

1152๋ฒˆ: ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜

์ฒซ ์ค„์— ์˜์–ด ๋Œ€์†Œ๋ฌธ์ž์™€ ๊ณต๋ฐฑ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ์ด ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 1,000,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค. ๋‹จ์–ด๋Š” ๊ณต๋ฐฑ ํ•œ ๊ฐœ๋กœ ๊ตฌ๋ถ„๋˜๋ฉฐ, ๊ณต๋ฐฑ์ด ์—ฐ์†ํ•ด์„œ ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ๋Š” ์—†๋‹ค. ๋˜ํ•œ ๋ฌธ์ž์—ด

www.acmicpc.net

My Solution

matches - ๋ฌธ์ž์—ด์—์„œ ๋™์ผํ•œ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค

  • using System.Text.RegularExpressions;

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            MatchCollection matches = Regex.Matches(s, " ");
            int cnt = matches.Count + 1;
            char[] chars = s.ToCharArray();
            cnt = (chars[0] != ' ') ? cnt : cnt-1;
            cnt = (chars[chars.Length-1] != ' ') ? cnt : cnt-1;

            Console.WriteLine(cnt);
        }
    }
}

Solution

๋‹ค๋ฅธ ๋ฐฉ๋ฒ• Trim / IsNullOrEmpty


using System;
using static System.Console;

class Program
{
    static void Main(string[] args)
    {
        // ์•ž๋’ค ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•œ ์ž…๋ ฅ๊ฐ’์„ ๋ฐ›๋Š”๋‹ค.
        string inputWord = ReadLine().Trim();

        // ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ๋‹จ์–ด๋งŒ ๋ฐฐ์—ด๋กœ ๋„ฃ๋Š”๋‹ค.
        string[] words = inputWord.Split();

        // ๋„์–ด์“ฐ๊ธฐ ์ฆ‰ ๊ณต๋ฐฑ๋ถ€๋ถ„์„ ํŒ๋‹จํ•  ๋กœ์ง
        // - ๊ณต๋ฐฑ์˜ ์ˆ˜๋ฅผ ์ฒดํฌํ•  count ๋ณ€์ˆ˜
        int count = 0;
        for (int i = 0; i < words.Length; i++)
        {
            if (String.IsNullOrEmpty(words[i]))
            {
                count++;
            }
        }

        // ๋‹จ์–ด์™€ ๊ณต๋ฐฑ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฐฐ์—ด - ๊ณต๋ฐฑ์˜ ์ˆ˜ = ๋‹จ์–ด ์ˆ˜
        WriteLine($"{words.Length - count}");
    }
}

๋Œ“๊ธ€