Reverse Sentence word by word

I : 2 I am happy today We want to win O : I ma yppah yadot eW tnaw ot niw

=>๊ณต๋ฐฑ ๋ฌธ์ž ๋˜๋Š” ์ค„๋ฐ”๊ฟˆ ๋ฌธ์ž๊ฐ€ ๋‚˜์˜ค๋ฉด ์Šคํƒ์ด ๋นŒ ๋•Œ๊นŒ์ง€ pop()์„ ํ•ด์„œ ๋ฌธ์ž๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

์‹ค์ˆ˜ํ•œ ๋ถ€๋ถ„ ๋ณต๊ธฐ

while(n-- >0) {
			String s = br.readLine();
			for(char c:s.toCharArray()) {
				//System.out.printf("c : %c",c);
				//System.out.println();
				if(c == ' ') {
					while(!st.isEmpty()) {
						System.out.print(st.pop());
						
					}
					System.out.print(c);
				}
				else {
					st.push(c);
				}
			}
		}

for-each ๋ฌธ์„ ๋Œ ๋•Œ ์ž…๋ ฅ String์˜ ๋ชจ๋“  character๋ฅผ ๋Œ๋ฉด์„œ ์ •์ƒ์ ์œผ๋กœ ์ถœ๋ ฅ๋์ง€๋งŒ ๋งˆ์ง€๋ง‰ ๋‹จ์–ด๊ฐ€ ์ •์ƒ ๋™์ž‘ํ•˜์ง€ ์•Š์•˜๋‹ค. ๊ทธ ์ด์œ ๋Š” ์Šคํƒ pop() ์กฐ๊ฑด์œผ๋กœ ๊ณต๋ฐฑ๋ฌธ์ œ๊ฐ€ ๋‚˜์˜ฌ ๋•Œ๋งŒ ๋‹ค๋ฃจ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ์Šคํƒ์— ๋งˆ์ง€๋ง‰ ๋‹จ์–ด์˜ character๊ฐ€ push๋˜๊ธด ํ•˜์ง€๋งŒ ๊ณต๋ฐฑ๋ฌธ์ž๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— pop(), ์ถœ๋ ฅํ•˜์ง€ ์•Š๊ณ  ์ข…๋ฃŒ๋๋‹ค.

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

  1. ์ž…๋ ฅ String์„ ๋ฐ›์„ ๋•Œ .readLine()์œผ๋กœ ๋ฐ›๊ณ , ์ €์žฅํ•  ๋•Œ ์ค„๋ฐ”๊ฟˆ ๋ฌธ์ž('\n')๋„ ํ•จ๊ป˜ ์ €์žฅํ•ด์ค€๋‹ค.

  2. pop() ์—ฐ์‚ฐ ์กฐ๊ฑด์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ˆ˜์ •ํ•œ๋‹ค.

while(n-- >0) {
			String s = br.readLine()+"\n";
			for(char c:s.toCharArray()) {
				//System.out.printf("c : %c",c);
				//System.out.println();
				if(c == ' ' || c == '\n') {
					while(!st.isEmpty()) {
						bw.write(st.pop());
					}
					bw.write(c);
				}
				else {
					st.push(c);
				}
			}
		}

Last updated