emmmm決定從今天開始刷leetcode。。。在這裏記錄一下我的答題思路和結果吧。可能不是最棒的。如果大家有更好的解題思路請多多指教~
給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。
原題:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
這裏利用了窗口滑動的效果。當已經確定[i, j]中沒有重複元素的時候,就可以直接看j+1在不在[i-1, j]中就可以了。最後不要忘記,如果字符串長度爲1的情況。
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
no_same = []
i = 0
max_len = 0
while i < len(s):
if s[i] not in no_same:
no_same.append(s[i])
i += 1
else:
max_len = max([max_len, len(no_same)])
no_same.pop(0)
max_len = max([max_len, len(no_same)])
return max_len
尋找兩個有序數組的中位數
原題:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
這裏我用了最簡單的合併,排序。但是時間複雜度是O(m+n),並不符合題目= =。(待完成)
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums1.extend(nums2)
new = sorted(nums1)
if len(new) % 2 == 0:
i = (0 + len(new)) // 2
middle = (new[i-1] + new[i]) / 2
else:
i = (0 + len(new) - 1) // 2
middle = new[i]
return middle
最長迴文子串
原題:https://leetcode-cn.com/problems/longest-palindromic-substring/
迴文,說簡單了就是順序讀和倒序讀是一樣的。或者說,從中心開始,依次往外依次擴散的字符都相同。因此,以這個爲思路,從中心出發。但是,字符串長度可能是奇數,也可能是偶數。因此需要考慮這兩種情況,以下是圖解:
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest_str = str()
for i in range(len(s)):
lstr = get_around_string(s, i, i)
rstr = get_around_string(s, i, i+1)
longe_str = lstr if len(lstr) >= len(rstr) else rstr
longest_str = longe_str if len(longe_str) >= len(longest_str) else longest_str
return longest_str
def get_around_string(s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
left += 1
return s[left: right]