惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 司徒正美
N
News and Events Feed by Topic
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
Help Net Security
Help Net Security
N
News and Events Feed by Topic
O
OpenAI News
L
LangChain Blog
F
Full Disclosure
A
About on SuperTechFans
The GitHub Blog
The GitHub Blog
GbyAI
GbyAI
Cloudbric
Cloudbric
W
WeLiveSecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
Attack and Defense Labs
Attack and Defense Labs
PCI Perspectives
PCI Perspectives
TaoSecurity Blog
TaoSecurity Blog
AI
AI
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Apple Machine Learning Research
Apple Machine Learning Research
C
CERT Recently Published Vulnerability Notes
T
The Exploit Database - CXSecurity.com
T
Threatpost
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Last Week in AI
Last Week in AI
雷峰网
雷峰网
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
P
Proofpoint News Feed
Latest news
Latest news
S
SegmentFault 最新的问题
J
Java Code Geeks
T
Threat Research - Cisco Blogs
H
Help Net Security
P
Privacy International News Feed

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1114. Print in Order 1242. Web Crawler Multithreaded Python Multi-threading bot ip Log Rate Limiter Most Frequent Call Chain remove prefix in a words list 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Keyword Tagging in Reviews with Overlapping Matches Retryer Function Implementation 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 1650. Lowest Common Ancestor of a Binary Tree III 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
Same Word of HTML Labels
北叶青藤 · 2026-04-06 · via 博客园 - 北叶青藤

You are given a string containing text and HTML-style tags (e.g., <div>, <p>, </div>). Your task is to determine if the "labels" or "tags" are correctly balanced.

  • Opening Tags: Stored as <tagname>.

  • Closing Tags: Stored as </tagname>.

  • Goal: Every opening tag must have a corresponding closing tag of the same word, and they must be closed in the reverse order they were opened (Last-In, First-Out).

Example 1 (Valid): "<div><p>Hello World</p></div>"

  • <div> opens.

  • <p> opens.

  • </p> matches the last opened tag (p).

  • </div> matches the first opened tag (div).

Example 2 (Invalid): "<div><p>Hello World</div></p>"

  • The div is closed before the p, which violates the nesting rules.

How to Solve It (Algorithm)

To solve this efficiently, you use a Stack data structure:

  1. Traverse the string and find every occurrence of a tag (text between < and >).

  2. If it's an opening tag (e.g., <b>): Push the word (e.g., "b") onto the stack.

  3. If it's a closing tag (e.g., </b>):

    • Check if the stack is empty. If it is, the string is invalid (closing tag with no opener).

    • Pop the top element from the stack.

    • Compare the popped word with the word in the closing tag. If they are not the same word, the string is invalid.

  4. Final Check: After parsing the entire string, the stack must be empty. If there are still words in the stack, it means some tags were never closed.

Example Logic Walkthrough

For the input: <div><span></span>

  • Step 1: Encounter div. Stack: ['div']

  • Step 2: Encounter span. Stack: ['div', 'span']

  • Step 3: Encounter /span. Pop span. Does span == span? Yes. Stack: ['div']

  • Result: String ends, but stack is not empty. Output: Invalid (or the name of the unclosed tag).

Common Variations

  • Self-closing tags: Some versions ask you to ignore tags like <img /> or <br /> which do not require a closing counterpart.

  • Return Value: Some versions ask for a boolean (true/false), while others ask you to return the name of the first tag that breaks the sequence.

 1 def check_html_labels(html_string):
 2     stack = []
 3     i = 0
 4     n = len(html_string)
 5     
 6     while i < n:
 7         # 1. Find the start of a tag
 8         if html_string[i] == '<':
 9             # Find the closing bracket for this tag
10             end_idx = html_string.find('>', i)
11             if end_idx == -1:
12                 break # Malformed HTML
13             
14             # Extract the content (e.g., "div" or "/div")
15             full_tag = html_string[i+1:end_idx]
16             
17             # Update loop index to continue after the '>'
18             i = end_idx + 1
19             
20             # 2. Handle Closing Tags
21             if full_tag.startswith('/'):
22                 tag_name = full_tag[1:]
23                 if not stack or stack[-1] != tag_name:
24                     return tag_name # Mismatch found
25                 stack.pop()
26             
27             # 3. Handle Opening Tags
28             else:
29                 # Handle potential attributes: <div class="test"> -> "div"
30                 tag_name = full_tag.split()[0]
31                 # Ignore self-closing tags like <br/>
32                 if not tag_name.endswith('/'):
33                     stack.append(tag_name)
34         else:
35             # Not a tag, just move to the next character
36             i += 1
37             
38     # Final check: If stack is empty, it's valid.
39     return True if not stack else stack[-1]
40 
41 # --- Test Cases ---
42 print(f"Result 1: {check_html_labels('<div><p>Valid</p></div>')}")  # True
43 print(f"Result 2: {check_html_labels('<div><span>Error</div>')}")   # span (it was never closed)
44 print(f"Result 3: {check_html_labels('<b><i>Mismatch</b></i>')}")    # i (b tried to close while i was top)