iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
自我挑戰組

Leetcode新手挑戰30天系列 第 3

#9 Palindrome Number

寫在開頭

因為Hash Table沒有這麼深刻的學習心得可以分享,就只先把查到覺得挺有用的資料先更新在Day2的文章裡,決定先繼續解下個題目Palindrome Number

題目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

這題想到最直接的方式是先把輸入數字變成列表,然後從最頭和最尾開始互相比較,一直比到最中間,有不一樣就回false.
應該會分成兩種狀況:
1.輸入長度是奇數,最中間那位不用比
2.輸入長度是偶數,會比到最中間兩位
這邊頭尾相比的方式和第一題Two Sum找和有點雷同,或許可以用相同的方法

我想到的sudocode是這樣:
inputlist = map(int, str(num))
k = 0
if (len(inputlist) % 2) == 0 :
for i in inputlist:
k += 1
if (inputlist[i] <> inputlist[-k]):
return false
if i == len(inputlist) // 2 :
return true
else:
for i in inputlist:
k += 1
if i == (len(inputlist) // 2 + 1) :
return true
if (inputlist[i] <> inputlist[-k]):
return false

最後在Leetcode上run過的code長這樣:

    def isPalindrome(self, x: int) -> bool:
        inputlist = list(map(int, str(x)))
        k = 1
        if (len(inputlist) % 2) == 0 :
            for i in inputlist:
                k += 1
                if inputlist[i] != inputlist[-k] :
                    return False
                if i == (len(inputlist) // 2) :
                    return True
        else:
            for i in inputlist:
                k += 1
                if i == (len(inputlist) // 2 + 1) :
                    return True
                if inputlist[i] != inputlist[-k] :
                    return False

發現寫錯的地方有兩點:
1.<>和!=都是不等於,但<>在這個地方會被判語法錯誤,因為python3把<>這個用法去掉了;
2.真假值要寫True/False,這個之前有發現Python是有大小寫敏感性的語言(Case-Sensitive).

最後想submit出去的時候發現testcase沒列完,如果輸入是"-10"會出現問題(冏)
晚點來查哪裡沒想清楚


上一篇
#1 Two Sum - 研究其他種解法
下一篇
#9 Palindrome Number - 繼續解
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言