LeetCode初級演算法練習 字串

2021-08-18 22:55:40 字數 1716 閱讀 6087

344

. 反轉字串

請編寫乙個函式,其功能是將輸入的字串反轉過來。

示例:

輸入:s = "hello"

返回:"olleh"

class solution:

def reversestring(self, s):

""":type s: str

:rtype: str

"""#[開始:結束:步進]步進預設=1

return s[::-1]

7

. 反轉整數

給定乙個 32 位有符號整數,將整數中的數字進行反轉。

示例 1:

輸入: 123

輸出: 321

示例 2:

輸入: -123

輸出: -321

示例 3:

輸入: 120

輸出: 21

注意:

假設我們的環境只能儲存 32 位有符號整數,其數值範圍是 [−231,  231 − 1]。根據這個假設,如果反轉後的整數溢位,則返回 0。

class solution:

def reverse(self, x):

""":type x: int

:rtype: int

"""

if x < 0:

r = int(str(x*-1)[::-1]) * -1

elif x < 10:

return x

else:

r = int(str(x)[::-1])

if r > 2**31 - 1 or r < -2**31:

r = 0

return r

387. 

字串中的第乙個唯一字元

給定乙個字串,找到它的第乙個不重複的字元,並返回它的索引。如果不存在,則返回 -1。

案例:

s = "leetcode"

返回 0.

s = "loveleetcode",

返回 2.

注意事項:您可以假定該字串只包含小寫字母。

class solution:

def firstuniqchar(self, s):

""":type s: str

:rtype: int

"""from collections import counter

c1 = counter(s)

a = list()

for i in c1.keys():

if c1[i] == 1:

if len(a) == 0:

return -1

else :

return min(a)

class solution:

def firstuniqchar(self, s):

""":type s: str

:rtype: int

"""#當索引列表為空時返回的是-1,不為空返回的是索引列表的最小值

import string

return min([s.index(ch) for ch in string.ascii_lowercase if s.count(ch) == 1] or [-1])

Leetcode初級演算法

不是很難的一道動態規劃的題,感覺做多了就記住了。class solution return dp n 此題想法就是,只要後面買的減去前面買的能大於0,就算在內,每次買完和max比較,大於max就記錄為max,如果買的sum小於0了,重新開始買,sum記為0 class solution if sum...

Leetcode 初級演算法02

了解的知識 1.空間複雜度 空間複雜度 space complexity 是對乙個演算法在執行過程中臨時占用儲存空間大小的量度。這樣子理解起來有點困難,我們又了解到當乙個演算法的空間複雜度為乙個常量,即不隨被處理資料量n的大小而改變時,可表示為o 1 舉兩個例子 a.陣列的隨機訪問就是o 1 b.鍊...

LeetCode初級演算法C

class solution temp len s i else if s i 0 s i 9 int i 0,j len 1 while i j else break if i j return true else return false 暴力求解,開闢了100010的陣列。class solu...