



풀이
효성
function solution(s) { const answer = []; for(const _s of s) { const stack = []; const arr = _s.split(''); let count = 0; for(let i = 0; i < arr.length; i++) { const third = arr[i]; if(stack.length > 1) { const second = stack.pop(); const first = stack.pop(); if(first === '1' && second === '1' && third === '0') { count++; continue; } else { stack.push(first, second, third); } } else { stack.push(third); } } if(!count) { answer.push(_s); } else { const list = []; const keyword = "011"; while(stack.length) { const last = stack.pop(); if(last === '0') { stack.push(last); break; } list.push(last); } while(count) { list.push(...keyword); count--; } while(stack.length) { list.push(stack.pop()); } const result = list.reverse().join(''); answer.push(result); } } return answer; }
재영
시간초과쓰...
function solution(s) { var answer = []; s.forEach(num => { let cnt = 0; let now = num; while (true) { const next = now.replace('110', ''); if (next === now) break; cnt += 1; now = next; } let lastIndex0 = -1; for (let i = now.length - 1; i >= 0; i -= 1) { if (now[i] === '0') { lastIndex0 = i; break; } } parse110 = ''; for (let i = 0; i < cnt; i += 1) { parse110 += '110' } answer.push(lastIndex0 === -1 ? parse110 + now : now.slice(0, lastIndex0 + 1) + parse110 + now.slice(lastIndex0 + 1)) }) return answer; }
다시 푼 결과!
const check = (stack) => { const stackLength = stack.length; const CHECK_VALUE = "011"; return ( stackLength >= 3 && stack[stackLength - 3] + stack[stackLength - 2] + stack[stackLength - 1] === CHECK_VALUE ); }; const solution = (s) => { var answer = []; s.forEach((num) => { let cnt = 0; let now = num.split(""); const stack = []; for (let i = 0; i < num.length; i += 1) { stack.push(now.pop()); if (check(stack)) { for (let i = 0; i < 3; i += 1) { stack.pop(); } cnt += 1; } } embedStrings = ""; for (let i = 0; i < cnt; i += 1) { embedStrings += "110"; } now = [...stack].reverse(); let embedIndex = -1; for (let i = now.length; i >= 0; i -= 1) { if (now[i] === "0") { embedIndex = i; break; } } const nowStr = now.join(""); const result = embedIndex === -1 ? embedStrings + nowStr : nowStr.slice(0, embedIndex + 1) + embedStrings + nowStr.slice(embedIndex + 1); answer.push(result); }); return answer; } (() => { const s = ["1110", "100111100", "0111111010"]; console.log(solution(s)); })();