단어뒤집기

_021119·2021년 4월 13일
0

알고리즘

목록 보기
8/9

스택을 이용한 문제 풀이!

public class fisrt {

	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		Stack<Character> stack = new Stack<>();

		int testCase = sc.nextInt();
		sc.nextLine();

		for(int i = 0; i< testCase; i++) {

			String str = sc.nextLine() + " ";
			for(int j = 0; j < str.length(); j++ ) {

				if(str.charAt(j) == ' ') {

					while(!stack.empty()) {
						System.out.print(stack.pop());
					}
				 System.out.print(' ');
				}else {
					stack.push(str.charAt(j));
				}
			}
			System.out.println();
		}
	}
}
  1. nextInt()로 받고 나서 다음 문장을 치기 위해 엔터를 치면 다음 for문 안의 nextLine()이 엔터까지 계산.....

    그렇기 때문에 nextInt()다음에 nextLine()한줄을 더 넣어준다.

  2. 받은 문장의 개수만큼 for 문을 돌리고, 단어는 공백으로 구분되어 있으므로 공백이 나오면 스택에 쌓아둔 단어들을 뽑아낸다.

    글자가 공백이 아니면 스택에 넣어주고 공백이면 스택이 다 비워질 때까지 pop한다.

    문장이 끝나면 똑같이 스택이 비워질 때까지 pop한다.

public class Main {

	public static void main(String[] args) throws IOException{

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Stack<Character> stack = new Stack<>();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int testCase = Integer.parseInt(br.readLine());

		for(int i = 0; i< testCase; i++) {

		String str = br.readLine() + "\n";

		for(int j = 0; j < str.length(); j++ ) {
				//System.out.println(str.toCharArray()[j]);
			if(str.charAt(j) == ' ' || str.toCharArray()[j] == ('\n')) {

				while(!stack.empty()) {
					bw.write(stack.pop());
				}
				bw.write(' ');
			}else {
				stack.push(str.toCharArray()[j]);
			}
		}
		bw.newLine();
		}
		bw.flush();
		bw.close();

	}
}

스캐너도 이용하고 버퍼도 사용해봤는데 시간초과랑 메모리 초과가 나온다..

다시 해봐야겟다..

profile
내가 정리하고 싶어서 쓰는 로오그

0개의 댓글