LeetCode初级算法练习——字符串

344反转字符串

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

示例:

输入:s = "hello"
返回:"olleh"
class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        #[开始:结束:步进]步进默认=1
        return s[::-1]
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:
            r = int(str(x*-1)[::-1]) * -1
        elif x < 10:
            return x
        else:
            r = int(str(x)[::-1])
        if r > 2**31 - 1 or r < -2**31:
            r = 0
        return r

387字符串中的第一个唯一字符

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

 

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


class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        from collections import Counter
        c1 = Counter(s)
        a = list()
        for i in c1.keys():
            if c1[i] == 1:
                a.append(s.index(i))
        if len(a) == 0:
            return -1
        else :
            return min(a)
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        #当索引列表为空时返回的是-1,不为空返回的是索引列表的最小值
        import string  
        return min([s.index(ch) for ch in string.ascii_lowercase if s.count(ch) == 1] or [-1])



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值