二刷 leetcode(5)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ANNILingMo/article/details/80957367

344反转字符串

请编写一个函数,其功能是将输入的字符串反转过来。

示例:

输入:s = "hello"
返回:"olleh"
代码:
class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        #### the first method
        # list_str = list(s)
        # res = []
        # for i in range(len(list_str)-1, -1, -1):
        #     res.append(list_str[i])
        # return "".join(res)
        #
        #### the second method
        return (s[::-1])
        
        #### the third method
        s = [i for i in s]
        n = len(s) // 2
        length = len(s)
        for i in range(n):
            temp = s[i]
            s[i] = s[length-1-i]
            s[length-i-1] = temp
        return "".join(s)
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:
        #     return x
        # xx = abs(x)
        # str_x = str(xx)
        # str_x = str_x[::-1]
        # if str_x[0] != '0' and x > 0:
        #     return int("".join(str_x))
        # elif str_x[0] != '0' and x < 0:
        #     return -int("".join(str_x))
        # elif str_x[0] == '0' and x > 0:
        #     return int("".join(str_x[1:]))
        # elif str_x[0] == '0' and x < 0:
        #     return -int("".join(str_x[1:]))
        
        #### 改进的方法
        if -10 < x < 10:
            return x
        str_x = str(x)
        if str_x[0] != '-':
            str_x = str_x[::-1]
            x = int(str_x)
        else:
            str_x = str_x[1:][::-1]
            x = int(str_x)
            x = -x
        return x  if -2**31 < x < 2 **31 -1 else 0
387 字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

代码:
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        #### the first method
        # ref = "abcdefghijklmnopqrstuvwxyz"
        # res = []
        # for w in ref:
        #     if (s.count(w) == 1):
        #         res.append(s.index(w))
        # if len(res) != 0:
        #     return min(res)
        # else:
        #     return -1
        
        #### the second method
        if len(s) == 0:
            return -1
        letter = set(s)
        index_list = []
        for w in letter:
            if s.count(w) == 1:
                index_list.append(s.index(w))
        return min(index_list) if len(index_list) > 0 else -1
                








猜你喜欢

转载自blog.csdn.net/ANNILingMo/article/details/80957367