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])