File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed
Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution (object ):
2+ def isValid (self , s ):
3+ """
4+ :type s: str
5+ :rtype: bool
6+ """
7+ mapParentheses = {"(" : ")" ,"[" : "]" , "{" : "}" }
8+ collectParentheses = []
9+
10+ for i , c in enumerate (s ):
11+ if i == 0 and c in mapParentheses .values ():
12+ return False
13+
14+ if c not in mapParentheses .keys () and c not in mapParentheses .values ():
15+ return False
16+
17+ if len (collectParentheses ) == 0 and c in mapParentheses .values ():
18+ return False
19+
20+ if mapParentheses .__contains__ (c ):
21+ collectParentheses .append (c )
22+ continue
23+
24+ lastCheck = collectParentheses [- 1 ]
25+ if mapParentheses .get (lastCheck ) == c :
26+ collectParentheses .pop ()
27+ continue
28+ else :
29+ return False
30+
31+ return len (collectParentheses ) == 0
32+
33+ print (Solution ().isValid ("(]" )) #false
34+ print (Solution ().isValid ("()[]{}" )) #true
35+ print (Solution ().isValid ("([])" )) #true
36+ print (Solution ().isValid ("(}{)" )) #false
37+ print (Solution ().isValid ("([{}])" )) #true
38+ print (Solution ().isValid ("(){}}{" )) #false
39+ print (Solution ().isValid ("(([]){})" )) #true
Original file line number Diff line number Diff line change 1+ class Solution (object ):
2+ def lengthOfLongestSubstring (self , s ):
3+ """
4+ :type s: str
5+ :rtype: int
6+ """
7+ if not s or len (s ) > 50000 :
8+ return 0
9+
10+ longestSubtstring = 1
11+ startIndex = {}
12+ startPosition = 0
13+
14+ for i , c in enumerate (s ):
15+ if c in startIndex and startIndex [c ] >= startPosition :
16+ startPosition = startIndex [c ] + 1
17+
18+ startIndex [c ] = i
19+ longestSubtstring = max (longestSubtstring , i - startPosition + 1 )
20+
21+ return longestSubtstring
22+
23+ print (Solution ().lengthOfLongestSubstring ("abcabcbb" )) #3
24+ print (Solution ().lengthOfLongestSubstring ("bbbbb" )) #1
25+ print (Solution ().lengthOfLongestSubstring ("pwwkew" )) #3
26+ print (Solution ().lengthOfLongestSubstring ("" )) #0
27+ print (Solution ().lengthOfLongestSubstring ("au" )) #2
28+ print (Solution ().lengthOfLongestSubstring ("aab" )) #2
You can’t perform that action at this time.
0 commit comments