LeetCode刷題筆記

2019/4/16

subject:771. Jewels and Stones
solution:

class Solution:
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        return sum(S.count(i) for i in J)

tips:
python中,count() 方法用于統(tǒng)計(jì)某個(gè)元素在列表中出現(xiàn)的次數(shù)宇整。


subject: 1021. Remove Outermost Parentheses
solution:

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        count = 0
        prev = None
        res = []
        left_n = 0
        right_n = 0
        j = 0
        for i in range(len(S)):
            if S[i] == "(":
                left_n += 1  # add 1 when left parenthesis
            else:
                right_n += 1  # add 1 when right
            if left_n == right_n:
                res.append(S[j + 1:i])  # add part when left_n = right_n
                j = i + 1  # because next first item will be cut, i + 1 gives j += 2 total
        return ''.join(res)       

2019/4/17

subject: 709. To Lower Case
solution1 :

class Solution:
    def toLowerCase(self, str: str) -> str:
        for i in str:
            if ord(i) in range(65,91):
                new = ord(i) + 32
                n = chr(new)
                str = str.replace(i,n)
        return str

solution 2:

class Solution(object):
    def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        stack = [ord(x) for x in str]
        for i in range(len(stack)):
            if stack[i] > 64 and stack[i] < 91:
                stack[i] += 32
        asw=[chr(x) for x in stack]
        
        return ''.join(asw)

tips:
Python join() 方法用于將序列中的元素以指定的字符連接生成一個(gè)新的字符串侨艾。
附:ASCII碼表


2019/4/22

subject: 2.Add two numbers
solution:

#
# @lc app=leetcode id=2 lang=python3
#
# [2] Add Two Numbers
#
# https://leetcode.com/problems/add-two-numbers/description/
#
# algorithms
# Medium (30.92%)
# Total Accepted:    831.3K
# Total Submissions: 2.7M
# Testcase Example:  '[2,4,3]\n[5,6,4]'
#
# You are given two non-empty linked lists representing two non-negative
# integers. The digits are stored in reverse order and each of their nodes
# contain a single digit. Add the two numbers and return it as a linked list.
# 
# You may assume the two numbers do not contain any leading zero, except the
# number 0 itself.
# 
# Example:
# 
# 
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
# 
# 
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        carry = 0
        root = n = ListNode(0)
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            n.next = ListNode(val)
            n = n.next
        return root.next

tips:
這道題涉及到Python數(shù)據(jù)結(jié)構(gòu)之鏈表(linked list)

root的作用:

2019/4/23

subject: [5] Longest Palindromic Substring
solution:

#
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# https://leetcode.com/problems/longest-palindromic-substring/description/
#
# algorithms
# Medium (27.00%)
# Total Accepted:    528.9K
# Total Submissions: 2M
# Testcase Example:  '"babad"'
#
# Given a string s, find the longest palindromic substring in s. You may assume
# that the maximum length of s is 1000.
# 
# Example 1:
# 
# 
# Input: "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# 
# 
# Example 2:
# 
# 
# Input: "cbbd"
# Output: "bb"
# 
# 
#

class Solution:
    def longestPalindrome(self, s):
        res = ""
        for i in range(len(s)):
            # odd case, like "aba"
            tmp = self.helper(s, i, i)
            if len(tmp) > len(res):
                res = tmp
            # even case, like "abba"
            tmp = self.helper(s, i, i+1)
            if len(tmp) > len(res):
                res = tmp
        return res

    # get the longest palindrome, l, r are the middle indexes
    # from inner to outer


    def helper(self, s, l, r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return s[l+1:r]

tips:
這道題主要是需要理解palindromic的格式混聊,即共有“a" "aa" "aba" 三種形式壹店。另外可以學(xué)習(xí)到的是在solution類中再編寫輔助函數(shù)調(diào)用的思想继控。
helper中的思想也值得注意停巷,l -= 1 r += 1的操作是為了讓掃描區(qū)域向str兩邊擴(kuò)散。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末恕酸,一起剝皮案震驚了整個(gè)濱河市堪滨,隨后出現(xiàn)的幾起案子蕊温,更是在濱河造成了極大的恐慌,老刑警劉巖义矛,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件发笔,死亡現(xiàn)場(chǎng)離奇詭異凉翻,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)制轰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來艇挨,“玉大人残炮,你說我怎么就攤上這事缩滨。” “怎么了脉漏?”我有些...
    開封第一講書人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵苞冯,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我侧巨,道長(zhǎng)舅锄,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任司忱,我火速辦了婚禮皇忿,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘坦仍。我一直安慰自己鳍烁,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開白布繁扎。 她就那樣靜靜地躺著幔荒,像睡著了一般糊闽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上爹梁,一...
    開封第一講書人閱讀 51,763評(píng)論 1 307
  • 那天右犹,我揣著相機(jī)與錄音,去河邊找鬼姚垃。 笑死傀履,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的莉炉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼碴犬,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼絮宁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起服协,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤绍昂,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后偿荷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體窘游,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年跳纳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了忍饰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡寺庄,死狀恐怖艾蓝,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情斗塘,我是刑警寧澤赢织,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站馍盟,受9級(jí)特大地震影響于置,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜贞岭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一八毯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瞄桨,春花似錦宪彩、人聲如沸讲婚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至白指,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間告嘲,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工橄唬, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人仰楚。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像僧界,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子捂襟,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容