ได้รับสตริงของ angle brackets (< >) ต้องเพิ่ม brackets ที่ต้นและท้ายเพื่อให้คู่ของ brackets สมดุลทุกคู่
ตัวอย่าง: '><<><' → เพิ่ม '<' หน้า และ '>>' หลัง → '<><<><>>'
ตัวอย่างโค้ด
const str = '><<><';
const buildPair = (str = '') => {
let count = 0, extras = 0;
for (const char of str) {
if (char === '>') {
if (count === 0) { extras++; } else { count--; }
} else { count++; }
}
const leadingTags = '<'.repeat(extras);
const trailingTags = '>'.repeat(count);
return leadingTags + str + trailingTags;
};
console.log(buildPair(str));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
><<><>>