[boj] 9093. 단어 뒤집기

 

9093번: 단어 뒤집기

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문장이 하나 주어진다. 단어의 길이는 최대 20, 문장의 길이는 최대 1000이다. 단어와 단어 사이에는

www.acmicpc.net

문장이 주어졌을 때, 
단어를 모두 뒤집어서
출력하는 프로그램을 작성하시오.

1. 문제 분석

이번 문제는 문장이 주어졌을 때, 단어의 순서는 유지 한 채로 단어 내 문자의 순서를 뒤집는 문제입니다.
후순으로 들어오는 문자를 우선 출력하는 문제로써 자료구조 StackLIFO ( Last-In First-Out ) 특성을 이용하겠습니다.
주의해야 할 점은 문장 내 단어의 순서는 유지되어야 합니다. 이를 위해 띄어쓰기 ( ' ' , 공백 )을 만나거나 문장이 종료될 때마다 Stack을 Flush 해주도록 하겠습니다.

2. 솔루션

const fs = require('fs');
const [T, ...sentences] = fs.readFileSync(process.platform ===
                                      'linux' ? '/dev/stdin' : 'input.txt')
                        .toString().split('\n').map(c => c.trim());
// Solution 1
let answer = [];
for (const sentence of sentences) {
    const stack = [];
    let charsOfFlippedSentence = [];
    const groupOfChars = sentence.split('');
    for (let i = 0; i < groupOfChars.length; i++) {
        const char = groupOfChars[i];
        // 공백을 만나게 되었을 때 Stack을 flush
        if (char === ' ') {
            while (stack.length !== 0) {
                charsOfFlippedSentence.push(stack.pop());
            }
            charsOfFlippedSentence.push(char);
        } else {
            stack.push(char);
            // 문장이 끝났을 때 Stack을 flush
            if(i === groupOfChars.length - 1) {
                while (stack.length !== 0) {
                    charsOfFlippedSentence.push(stack.pop());
                }
            }
        }
    }
    answer.push(charsOfFlippedSentence.join(''));
}

console.log(answer.join('\n'));

3. 마치며

이 문제는 순서가 있는 원소들을 역순으로 전환한다는 점에서 전형적인 Stack을 활용한 알고리즘 문제의 예였습니다. 사실 Stack을 활용하지 않고도 Javascript 내장 함수인 reverse( )를 통해 더 단순하게 푸는 방법도 존재합니다.
하지만 문제 출제자의 의도는 아마도 Stack을 말한 것이겠죠?
reverse( ) 내장함수를 활용한 예로 글을 마치도록 하겠습니다.
감사합니다.
const fs = require('fs');
const [T, ...sentences] = fs.readFileSync(process.platform ===
                                      'linux' ? '/dev/stdin' : 'input.txt')
                        .toString().split('\n').map(c => c.trim());

for (const sentence of sentences) {
    let groupOfFlippedWords = [];
    const words = sentence.split(' ');
    for (const word of words) {
        groupOfFlippedWords.push([...word].reverse().join(''));
    }
    console.log(groupOfFlippedWords.join(' '));
}

'알고리즘-문제풀이' 카테고리의 다른 글

[boj] 6588. 골드바흐의 추측  (1) 2023.03.15
[boj] 1158. 요세푸스 문제  (0) 2023.03.13
[boj] 1406. 에디터  (0) 2023.03.09
[boj] 1874. 스택 수열  (0) 2023.03.06
[boj] 9012. 괄호  (1) 2023.03.04