문자열 문제, 전광판

이창호·2023년 2월 23일
0

알고리즘

목록 보기
1/4

문제 :
문자열 s = "Snowball" 이 있다.
전광판의 크기는 n=5, 시간(초)는 t이다.
전광판은 1초마다 한글자씩 보여준다.
예시 :
0초
"_____"

1초
"____S"

4초
"_Snow"

9초
"ball_"

10초
"all__"

13초
"_____"

14초
"____S"

나의 생각

  • 전광판은 결국, "_" * n번 + "Snowman" == "_____Snowman"이 한칸씩 움직이면서 n개 만큼만 출력되면 된다. '문자열을 합친다'는 생각을 하면 문제는 쉽다.

  • 항상 0번 인덱스부터 n번 인덱스 까지 출력을 한다.

  • 그전에 합친문자열이 t초마다 한칸씩 뒤로가도록 하면된다.

구현

import java.io.*;
import java.util.*;
public class Bord01 {
    public static void main(String[] args) throws IOException {
        String s = "Snowball"; // 출력할 광고문자
        int n=5; //전광판의 크기
        int t=13; // 시간(초)
        solution(s,n,t);
    }
    public static void solution(String s, int n, int t)
    {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<n;i++)
        {
            sb.append("_"); // 전관판의 크기만큼 "_"를 추가하낟.
        }
        sb.append(s); // 문자열 Snowball을 합쳐준다.
        String bord = sb.toString(); //전광판에 들어갈 글자들 ("_____Snowball") 이중, 0번에서 n번 까지만 출력해주면 된다.
        
        //시간 t초에 따른 움직임
        for(int i=0;i<t;i++)
        {
            //t초마다, 맨앞의 글자를 맨뒤로 보낸다.
            sb = new StringBuilder();
            sb.append(bord.substring(1,bord.length())); // 
            sb.append(bord.charAt(0));
            bord = sb.toString();
        }

        //위과정을 마치고, 0번에서 n번 까지만 출력한다.
        System.out.println(bord.substring(0,n));

    }

}

Queue를 이용한 구현

public static void solution(String s, int n, int t)
    {
        Queue<Character> q = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<n;i++)
        {
            q.offer('_'); // n개 만큼 큐에 넣기
        }
        for(int i=0;i<s.length();i++){
            q.offer(s.charAt(i)); // 문자열 한글자씩 큐에 넣기
        }


        for(int i=0;i<t;i++) // t초마다 움직임
        {
            q.offer(q.poll()); // 맨 앞글자 맨뒤로
        }
        for(int i=0;i<n;i++)
            sb.append(q.poll()); //n개만큼만 출력

        System.out.println(sb.toString()); // 출력


    }

}
profile
어떻게든 해결한다.

0개의 댓글