Chrome Pointer

2023年6月15日 星期四

Strings Pyhton - LeetCode

  Reverse String

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18



  Reverse Integer

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
42
43
44
45
46
47
48
49
50
51

46
47


  First Unique Character in a String


class Solution: def firstUniqChar(self, s: str) -> int: dic={} for i in range(len(s)): if s[i] in dic: dic[s[i]]="#" else: dic[s[i]]=i for d in dic: if dic[d]!="#": return dic[d] return -1


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


  Valid Anagram

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        #Input: s = "anagram", t = "nagaram"
        
        
        if sorted(s)==sorted(t):
            return True
        else:
            return False
class Solution: def isAnagram(self, s: str, t: str) -> bool: dic={} dic2={} if len(s)!=len(t): return False for i in range(len(s)): if s[i] in dic: dic[s[i]]+=1 else: dic[s[i]]=1 if t[i] in dic2: dic2[t[i]]+=1 else: dic2[t[i]]=1 if dic==dic2: return True else: return False


  Valid Palindrome


Your input

"0P"


class Solution:
    def isPalindrome(self, s: str) -> bool:
        #中文當中是指倒正著念和反著念都相同的句子
        #Input: s = "A man, a plan, a canal: Panama"
        #Input: s = "A ma MA"
        #Two pointers

        sta=0
        end=len(s)-1
        s = s.lower() #把字串裡面所有字元變成小寫
        
        while sta<end:
            if not s[sta].isalnum(): #確認字元是否為 「alphabet 與 numeric」字母和數字
                sta+=1
            elif not s[end].isalnum():
                end-=1
            elif s[sta]==s[end]: #如果前面 和 後面的字元一樣 就代表前後文一樣
                sta+=1
                end-=1
            else:
                return False
            
        return True

    
'''
.lower()和.upper()要學
補充 isalpha(), isalnum()
因為本題敘述中提到 removing all non-alphanumeric characters,因此需要保留「alpha 與 numeric」,
不能只判斷 “字母” 使用 isalpha()。
'''


  String to Integer (atoi)

Example 1:

Your input

"+-12"
"words of 108"
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
44
  Implement strStr()      
45