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"]
class Solution:
2def reverseString(self, s: List[str]) -> None:
3"""
4Do not return anything, modify s in-place instead.
5"""
6#Input: s = ["h","e","l","l","o"]
7
8start = 0
9end =len(s)-1
10
11
12while start<end:
13s[start], s[end] = s[end], s[start]
14start+=1
15end-=1
16
17
18return s
Reverse Integer
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
class Solution:
2def reverse(self, x: int) -> int:
3#Input: x = 123
4#Output: 321
5
6if x>0:
7a=str(x) #Input: x = 123是int, 要改成string 才能[::-1]
8b=a[::-1] # 321
9ans=int(b)
10else:
11a=str(x*-1) # 乘以負號讓它變正
12b=a[::-1] # 變正後進行扭轉
13ans=-int(b) # 扭轉完成再把負號加回去
14
15# 考虑溢出
16if ans<2**31-1 and ans>=-2**31 :
17return ans
18else:
19return 0
20'''
21[::-1] 顺序相反操作
22[-1] 读取倒数第一个元素
23[3::-1] 从下标为3(从0开始)的元素开始翻转读取
24
25a=[1,2,3,4,5]
26print(a)
27[ 1 2 3 4 5 ]
28
29[ : n] 代表列表中的第一項到第n項
30
31print(a[-1]) 取最後一個元素
32結果:[5]
33
34print(a[:-1]) 除了最後一個取全部
35結果:[ 1 2 3 4 ]
36
37print(a[::-1]) 取從後向前(相反)的元素
38結果:[ 5 4 3 2 1 ]
39
40print(a[3::-1]) 取從下標為3的元素翻轉讀取 結果:[4 3 2 1 ]
42
43print(a[1:]) 取第二個到最後一個元素
44結果:[2 3 4 5]
45
46print(a[::-2]) 倒數跳兩格
47結果:[5, 3, 1]
48
49print(a[::2]) 往前跳兩格
50結果:[1, 3, 5]
5146https://cloud.tencent.com/developer/article/1608978
47'''
First Unique Character in a String
Example 1:
Input: s = "leetcode" Output: 0
Example 2:
Input: s = "loveleetcode" Output: 2
Example 3:
Input: s = "aabb" Output: -1
class Solution:
2def firstUniqChar(self, s: str) -> int:
3#Input: s = "leetcode"
4
5worddict = Counter(s)
6print(worddict)
7#計算個欄位的數量
8#Counter({'e': 3, l': 1, 't': 1, 'c': 1, 'o': 1, 'd': 1})
9#Counter 是 Python 裡面自帶的模組,可以快速統計 List 內的元件,數量由大到小排序。
10
11for idx, ele in enumerate(s): #列舉 枚舉 #idx代表位置 ; ele元素名稱
12if worddict[ele] >= 2: # has duplicate
13pass #沒有意義 但因為if內必須至少有一行code
14else: # no duplicate
15return idx
16
17return -1
18
19
20'''
21https://www.wongwonggoods.com/all-posts/interview_prepare/python_leetcode/leetcode-python-387/
22counter 屬於 dict 的子資料型態,是專門設計用來計數的,
23我們將一個內容丟入 counter 中,
24會回傳一個相當於 dict 的資料型態,
25其中 key 代表的是「對應的元素」,而 value 代表的是「對應的數量」,
26我們可以直接把內容丟入 counter,並得到結果。
27
28https://www.runoob.com/python/python-func-enumerate.html
29
30for 循环使用 enumerate
31>>> seq = ['one', 'two', 'three']
32>>> for i, element in enumerate(seq):
33... print i, element
34...
350 one
361 two
372 three
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
Valid Palindrome
Example 1:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
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:
Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in, the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) ^ The parsed integer is 42. Since 42 is in the range [-231, 231 - 1], the final result is 42.
Example 2:
Input: s = " -42" Output: -42 Explanation: Step 1: " -42" (leading whitespace is read and ignored) ^ Step 2: " -42" ('-' is read, so the result should be negative) ^ Step 3: " -42" ("42" is read in) ^ The parsed integer is -42. Since -42 is in the range [-231, 231 - 1], the final result is -42.
Example 3:
Input: s = "4193 with words" Output: 4193 Explanation: Step 1: "4193 with words" (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
class Solution:
2def myAtoi(self, s: str) -> int:
3#Input: s = "42"
4
5s = s.lstrip() #lstrip() 函數用來去除字串左邊的空白字元。
6
7if not s:
8return 0
9
10i = 0
11sign = 1 #確認是屬於正數還是負數
12
13if s[i] == "+":
14i += 1
15elif s[i] == "-":
16i += 1
17sign = -1
18
19Ans = 0
20
21while i < len(s):
22curr = s[i]
23if not curr.isdigit(): #如果字符串只包含數字則返回 True 否則返回 False。
24break
25else:
26Ans = Ans * 10 + int(curr)
27
28i += 1
29
30Ans *=sign #乘以正數或負數
31
32if Ans > 2**31 - 1:
33return 2**31 - 1
34
35elif Ans < -2**31:
36return -2**31
37
38else:
39return Ans
41#補充 : Python isdigit() 方法只對 0 和 正數才有效。
#https://www.youtube.com/watch?v=YA0LYrKI1CQ&ab_channel=CrackingFAANG
43#https://badgameshow.com/steven/python/python-string-strip-lstrip-rstrip/
44
45