当前位置:网站首页>[leetcode] 20. Valid brackets
[leetcode] 20. Valid brackets
2022-07-07 23:48:00 【Xiaoqu classmate】
20、 Valid parenthesis
subject :
Given one only includes ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ String s , Determines whether the string is valid .
Valid string needs to meet :
Opening parentheses must be closed with closing parentheses of the same type .
The left parenthesis must be closed in the correct order .
Example 1:
Input :s = "()"
Output :true
Example 2:
Input :s = "()[]{}"
Output :true
Example 3:
Input :s = "(]"
Output :false
Example 4:
Input :s = "([)]"
Output :false
Example 5:
Input :s = "{[]}"
Output :true
Tips :
1 <= s.length <= 10^4
s Brackets only ‘()[]{}’ form
Their thinking :
- First, if the string can form valid parentheses , Then the length must be even
- We can iterate through strings , If the left bracket is encountered, it will be temporarily stored , Expect a closing parenthesis to match it
- If a closing bracket is encountered, check whether it matches the latest temporary bracket .
- This is consistent with the first in and last out characteristics of stack data structure . So we can prepare a stack to store bracket pairs
- When traversing a string , If you encounter an open bracket, put it on the stack , If the right bracket is encountered, judge whether the right bracket can match the top element of the stack , At the end of the loop, it is also necessary to determine whether the stack is empty , If it's not empty , Is not a string matching valid parentheses
Complexity analysis :
Time complexity :O(n), among n Is string s The length of .
Spatial complexity :O(n+∣Σ∣), among Σ Represents the character set , The string in this question only contains 6 Kind bracket ,∣Σ∣=6. The number of characters in the stack is O(n), The space used by the hash table is O(∣Σ∣), Add to get the total space complexity .
Specific code :
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {
{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}
边栏推荐
- 光流传感器初步测试:GL9306
- Postgres timestamp to human eye time string or millisecond value
- Take you hand in hand to build Eureka server with idea
- At the age of 35, I made a decision to face unemployment
- Access database query all tables SQL
- What if once again forgets the login password of raspberry pie? And you don't have a monitor yet! Today, I would like to introduce a method
- C method question 2
- Flash encryption process and implementation of esp32
- C number of words, plus ¥, longest word, average value
- Enterprise application demand-oriented development of human resources department, employee attendance records and paid wages business process cases
猜你喜欢
How did a fake offer steal $540million from "axie infinity"?
Connect diodes in series to improve voltage withstand
Ora-02437 failed to verify the primary key violation
一鍵免費翻譯300多頁的pdf文檔
HB 5469 combustion test method for non-metallic materials in civil aircraft cabin
About the difference between ch32 library function and STM32 library function
The file format and extension of XLS do not match
C method question 1
Open source hardware small project: anxinco esp-c3f control ws2812
SAP HR social work experience 0023
随机推荐
Data Lake (XV): spark and iceberg integrate write operations
【汇总】看过的一些Panel与视频
Ora-02437 failed to verify the primary key violation
Pycharm basic settings latest version 2022
Dependency injection
Jisuan Ke - t3104
ASP. Net query implementation
C method question 2
Postgres timestamp to human eye time string or millisecond value
[stm32+esp8266 connects to Tencent cloud IOT development platform 3] stm32+esp8266-01s dynamically registers devices on Tencent cloud (at instruction mode) -- with source code
Interface
通达信买基金安全吗?
P1055 [noip2008 popularization group] ISBN number
Balanced binary tree [AVL tree] - insert, delete
redis缓存工具类,值得拥有~
激光slam学习(2D/3D、偏实践)
Magic fast power
c—线性表
Enumeration, simulation, and sorting
P1308 [noip2011 popularity group] count the number of words