seunghyun Note
[백준] 1316번 : 그룹 단어 체커 with JS 본문
728x90
반응형
링크 : https://www.acmicpc.net/problem/1316
문제 풀이
1. 입력 숫자(n) 만큼 배열 순회
for (let i = 0; i < n; i++) {
sum += isGroup(arr[i]);
}
2.isGroup 함수
function isGroup(str) {
let compressed = "";
for (let i = 0; i < str.length; i++) {
let currentChar = str[i];
let nextChar = str[i + 1];
//console.log(currentChar, nextChar);
compressed += currentChar;
while (currentChar === nextChar) {
i++;
nextChar = str[i + 1];
}
}
- 문자열의 첫째값과 다음값을 따로 저장해놓는다.
let currentChar = str[i];
let nextChar = str[i + 1];
compressed (초기화된 문자열)에 첫째값(currentChar)값을 더해준다.
- 반복 문자를 줄이기 위해 첫째값과 다음값이 같다면 index(i)의 값을 증가시키고 그만큼 다음값(nextChar)을 바꿔준다.
while (currentChar === nextChar) {
i++;
nextChar = str[i + 1];
}
반복을 줄여서 happy -> hapy , aaaaaa -> a, abaab ->abab 로 문자열을 바꿔준다.
- set을 통해 배열 비교 해주기
compressed 문자열을 set에 저장해서 set 과 compressed 함수를 비교해서 길이가 같다면 1, 0을 반환해서
배열에 sum 에 더해준다.
const set = new Set(compressed);
if (set.size === compressed.length) return 1;
else return 0;
최종 코드
const fs = require("fs");
const [n, ...arr] = fs.readFileSync("예제.txt").toString().trim().split("\n");
// const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
let sum = 0;
for (let i = 0; i < n; i++) {
sum += isGroup(arr[i]);
}
console.log(sum);
function isGroup(str) {
let compressed = "";
for (let i = 0; i < str.length; i++) {
let currentChar = str[i];
let nextChar = str[i + 1];
//console.log(currentChar, nextChar);
compressed += currentChar;
while (currentChar === nextChar) {
i++;
nextChar = str[i + 1];
}
}
//console.log(compressed);
const set = new Set(compressed);
if (set.size === compressed.length) return 1;
else return 0;
}
728x90
반응형
'코딩테스트 > 백준' 카테고리의 다른 글
최대힙 (0) | 2024.02.26 |
---|---|
[백준] 1991번 : 트리 순회 with JS (1) | 2024.02.12 |
[백준] 28279번 : 덱 2 with JS (0) | 2024.01.25 |
[백준] 11866번 : 요세푸스 문제 0 with JS (1) | 2024.01.24 |
[프로그래머스] - 2016년 with JAVA (0) | 2024.01.10 |