99클럽 코테 스터디 13일차 TIL - 단어순서 뒤집기
오늘의 문제
백준 - 12605번: 단어순서 뒤집기
문제내용과 풀이
스페이스로 띄어쓰기 된 단어들의 리스트가 주어질때, 단어들을 반대 순서로 뒤집어라.
각 라인은 w개의 영단어로 이루어져 있으며, 총 L개의 알파벳을 가진다.
각 행은 알파벳과 스페이스로만 이루어져 있다. 단어 사이에는 하나의 스페이스만 들어간다.
입력
첫 행은 N이며, 전체 케이스의 개수이다.
N개의 케이스들이 이어지는데, 각 케이스는 스페이스로 띄어진 단어들이다. 스페이스는 라인의 처음과 끝에는 나타나지 않는다.
N과 L은 다음 범위를 가진다.
- N = 5
- 1 ≤ L ≤ 25
출력
각 케이스에 대해서, 케이스 번호가 x일때 "Case #x: " 를 출력한 후 그 후에 이어서 단어들을 반대 순서로 출력한다.
예시
this is a test -> Case #1: test a is this
foobar -> Case #2: foobar
all your base -> Case #3: base your all
내 풀이
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 1; i <= n; i++) {
String line = scanner.nextLine();
String[] words = line.split(" ");
String reversedLine = "";
for (int j = words.length - 1; j >= 0; j--) {
reversedLine += words[j];
if (j > 0) {
reversedLine += " ";
}
}
System.out.println("Case #" + i + ": " + reversedLine);
}
scanner.close();
}
}
단어마다 거꾸로 붙여서 해결하는 것도 가능하기는 하다.
StringBuilder
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 1; i <= n; i++) {
String line = scanner.nextLine();
String[] words = line.split(" ");
StringBuilder reversedLine = new StringBuilder();
for (int j = words.length - 1; j >= 0; j--) {
reversedLine.append(words[j]);
if (j > 0) {
reversedLine.append(" ");
}
}
System.out.println("Case #" + i + ": " + reversedLine.toString());
}
scanner.close();
}
}
+= 연산 대신 Stringbuilder의 append() 를 사용해 문자열을 조합할 수 있다.
StringBuilder를 사용하는 것이 좋은 이유는 문자열을 반복적으로 연결할 때 성능이 훨씬 효율적이기 때문이라고 한다.
* String 객체는 불변(immutable)이다. 한 번 생성된 문자열 객체는 변경할 수 없으며, 문자열을 수정하는 경우 새로운 String 객체가 생성된다. 예를 들어, 문자열을 반복해서 + 연산으로 연결하는 경우, 매번 새로운 문자열 객체를 만들고 기존 문자열과 합쳐야 하기 때문에 메모리와 CPU를 더 많이 사용하게 된다.
* StringBuilder는 가변(mutable) 객체로, 문자열을 변경할 때 새로운 객체를 만들지 않고 내부 버퍼에서 직접 수정한다.
따라서 문자열을 여러 번 연결하거나 수정할 때 메모리와 CPU를 덜 사용하게 된다.
Stack
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 1; i <= n; i++) {
String line = scanner.nextLine();
String[] words = line.split(" ");
Stack<String> stack = new Stack<>();
for (String word : words) {
stack.push(word);
}
StringBuilder reversedLine = new StringBuilder();
while (!stack.isEmpty()) {
reversedLine.append(stack.pop());
if (!stack.isEmpty()) {
reversedLine.append(" ");
}
}
System.out.println("Case #" + i + ": " + reversedLine.toString());
}
scanner.close();
}
}
문제 힌트가 스택/큐라 스택을 이용해서도 풀 수 있는데, 왜 스택을 써야되는지는 잘 모르겠다...
js
let text = "hello";
let reversedText = text.split('').reverse().join('');
console.log(reversedText); // "olleh"
js는 배열로 변환해서 문자열을 뒤집는게 표준적인 방식이라고 한다.