Leetcode Data Structure [415 | 409]

415. Add Strings

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Solution:

class Solution:
    def addStrings(self, num1, num2):
        
        def stringnum(num):
            resource = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4,
                        "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
            result = 0
            for d in num:
                result = result * 10 + resource[d]
            return result
        
        return str(stringnum(num1) + stringnum(num2))

Feedback:

Runtime: 68 ms, faster than 41.93% of Python3 online submissions for Add Strings.

Memory Usage: 14.1 MB, less than 71.23% of Python3 online submissions for Add Strings.


409. Longest Palindrome

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

Solution:

class Solution:
    def longestPalindrome(self, s):
        result = []
        answer = 0
        for d in set(s):
            if s.count(d) >= 2:
                result.insert(0, [d, d]*(s.count(d) // 2))
            answer += (s.count(d) // 2)*2
        
        if len(s) == answer:
            return answer
        return answer+1

Feedback:

Runtime: 45 ms, faster than 56.32% of Python3 online submissions for Longest Palindrome.

Memory Usage: 13.8 MB, less than 83.58% of Python3 online submissions for Longest Palindrome.

To be continued... : )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值