กำหนดข้อความและลิสต์ patterns ห่อ substring ที่ตรง patterns ด้วย <b> และ </b> รวม tag ที่ติดหรือทับซ้อนกัน
ตัวอย่าง: text = "thisissampleline", patterns = ["this", "ssam", "sample"] → "<b>this</b>i<b>ssample</b>line"
ขั้นตอน
- สร้าง boolean array
boldขนาดเท่าข้อความ - สำหรับแต่ละตำแหน่ง i และ pattern p: หาก text[i:] เริ่มด้วย p → ทำเครื่องหมาย bold[i:i+len(p)] = True
- สร้างผลลัพธ์: เพิ่ม
<b>ตอนเริ่ม bold,</b>ตอนจบ bold
ตัวอย่างโค้ด
class Solution:
def solve(self, text, patterns):
n = len(text)
bold = [False] * n
for i in range(n):
for p in patterns:
if text[i:].startswith(p):
for j in range(len(p)):
bold[i + j] = True
ans = ""
for i in range(n):
if bold[i] and (i == 0 or not bold[i - 1]):
ans += ""
ans += text[i]
if bold[i] and (i == n - 1 or not bold[i + 1]):
ans += ""
return ans
ob = Solution()
text = "thisissampleline"
patterns = ["this", "ssam", "sample"]
print(ob.solve(text, patterns))
# thisissampleline
อินพุต
"thisissampleline", ["this", "ssam", "sample"]
เอาต์พุต
thisissampleline