Outdated/Algorithm Solution

[BOJ] 9935번 문자열 폭발

해달 2020. 7. 6. 08:00

복기

괄호 쌍 찾는 문제와 비슷하다.


코드

  • C++ 17


#include <iostream>

#include <string>

 

using namespace std;

 

string Word, Bomb;

 

// 끝에서부터 비교해 나가면 중첩되었더라도 삭제할 수 있다.

bool CanExplode(const string& str)

{

    if (str.back() != Bomb.back() || str.size() < Bomb.size())

        return false;

    

    for (int i = 0; i < Bomb.size(); ++i)

    {

        if (str[str.size() - 1 - i] != Bomb[Bomb.size() - 1 - i])

            return false;

    }

    

    return true;

}

 

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    cout.tie(nullptr);

 

    cin >> Word >> Bomb;

    string ans;

    for (int i = 0; i < Word.size(); ++i)

    {

        ans.push_back(Word[i]);

 

        if (CanExplode(ans))

            ans.erase(ans.size() - Bomb.size());

    }

 

    if (ans.empty())

        cout << "FRULA";

    else

        cout << ans;

}


  • C# 6.0


using System;

using System.Text;

 

namespace Csharp

{

    class Program

    {

        static string Word, Bomb;

        

        static void Main(string[] args)

        {

            Word = Console.ReadLine();

            Bomb = Console.ReadLine();

            StringBuilder sb = new StringBuilder();

 

            for (int i = 0; i < Word.Length; ++i)

            {

                sb.Append(Word[i]);

 

                if (CanExplode(sb))

                    sb.Remove(sb.Length - Bomb.Length, Bomb.Length);

            }

 

            if (sb.Length == 0)

                Console.WriteLine("FRULA");

            else

                Console.WriteLine(sb.ToString());

        }

 

        static bool CanExplode(StringBuilder sb)

        {

            if (sb.Length < Bomb.Length)

                return false;

            if (sb[sb.Length - 1] != Bomb[Bomb.Length - 1])

                return false;

 

            for (int i = 0; i < Bomb.Length; ++i)

            {

                if (sb[sb.Length - 1 - i] != Bomb[Bomb.Length - 1 - i])

                    return false;

            }

 

            return true;

        }

    }

}


  • Python 3


Word = input()

Bomb = input()

 

Ans = []

Len = len(Bomb)

for ch in Word:

    Ans.append(ch)

 

    if ch == Bomb[-1] and Bomb == "".join(Ans[-Len:]):

        del Ans[-Len:]

 

if len(Ans):

    print("".join(Ans))

else:

    print("FRULA")


'Outdated > Algorithm Solution' 카테고리의 다른 글

[BOJ] 5585번 거스름돈  (0) 2020.10.07
[BOJ] 1544번 사이클 단어  (0) 2020.06.29
[BOJ] 1074번 Z  (0) 2020.06.29
[BOJ] 1016번 제곱 ㄴㄴ수  (0) 2020.06.22
[BOJ] 1476번 날짜 계산  (0) 2020.06.22