leetcode - 刷题记录-探索初级算法-字符串

  1. 反转字符串
    1. 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

      不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

      你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

    2. class Solution:
          def reverseString(self, s: List[str]) -> None:
              """
              Do not return anything, modify s in-place instead.
              """
              start = 0
              end = len(s)-1
              while start<end:
                  s[start],s[end] = s[end],s[start]
                  start = start + 1
                  end = end - 1
              return s

      通过

  2. 整数反转

    1. 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转.。

    2. class Solution:
          def reverse(self, x: int) -> int:
              if -10<x<10:
                  return x
              elif x<0:
                  flag = 1
                  x = -x
              else:
                  flag = 0
              #import math
              #n = int(math.log(x)/math.log(10))
              n = len(list(str(x)))-1
              res = 0
              while x > 0:
                  res = (x%10)*10**n + res
                  x = int(x/10)
                  n = n-1
              res = -res if flag==1 else res
              res = 0 if res<-2**31 or res>2**31-1 else res
              return res

      通过

  3. 字符串中的第一个唯一字符

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

    2. class Solution:
          def firstUniqChar(self, s: str) -> int:
              dic_1 = {}
              dic_2 = {}
              for i in range(len(s)):
                  if s[i] in dic_1:
                      del dic_1[s[i]]
                      dic_2[s[i]] = i
                  else:
                      if s[i] in dic_2:
                          continue
                      else:
                          dic_1[s[i]] = i
              if dic_1 == {}:
                  return -1
              else:
                  
                  res = len(s)
                  for i in dic_1:
                      if dic_1[i] < res:
                          res = dic_1[i]
                  return res
                  # 104ms
                  res = min([dic_1[i] for i in dic_1])
                  return res
                  # 112ms

      通过

  4. 有效的字母异位词

    扫描二维码关注公众号,回复: 10335502 查看本文章
    1. 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

    2. class Solution:
          def isAnagram(self, s: str, t: str) -> bool:
             
              if len(s) != len(t):
                  return False
              
              # solution1
              t = list(t)
              for i in s:
                  if i in t:
                      t.remove(i)
              return t==[]
                  

      通过。但是是暴力解法,有更好的解法。

  5. 验证回文字符串

    1. 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

      说明:本题中,我们将空字符串定义为有效的回文串。

    2. class Solution:
          def isPalindrome(self, s: str) -> bool:
              # 65,97,48
              
              dic = {}
              for i in range(128):
                  dic[chr(i)] = i
              #print(dic)
              i = 0
              j = len(s)-1
              while i<j:
                  while not (dic['A']<=dic[s[i]]<=dic['Z'] or dic['a']<=dic[s[i]]<=dic['z'] or dic['0']<=dic[s[i]]<=dic['9']) and i < j:
                      i += 1
                  while not (dic['A']<=dic[s[j]]<=dic['Z'] or dic['a']<=dic[s[j]]<=dic['z'] or dic['0']<=dic[s[j]]<=dic['9']) and i < j:
                      j -= 1
                  si = dic[s[i]] if dic[s[i]]<=dic['Z'] else dic[s[i]]-32
                  sj = dic[s[j]] if dic[s[j]]<=dic['Z'] else dic[s[j]]-32
                  if si == sj:
                      i += 1
                      j -= 1
                  else:
                      return False
              return True

      通过

  6. 字符串转换整数 (atoi)

    1. 请你来实现一个 atoi 函数,使其能将字符串转换成整数。

      首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。

      当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

      该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。

      注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。

      在任何情况下,若函数不能进行有效的转换时,请返回 0。

    2. class Solution:
          def myAtoi(self, str: str) -> int:
              dic = {}
              for i in range(ord('0'),ord('9')+1):
                  dic[chr(i)] = i
                  
              if len(str) == 0:
                  return 0
              
              elif str[0] in dic or str[0] == ' ' or str[0]=='+' or str[0]=='-':
                  i = 0
                  while i < len(str) and str[i] == ' ':
                      i += 1
                  str = str[i:]
                  if len(str) == 0:
                      return 0
                  
                  flag = 1
                  if str[0] == '+':
                      str = str[1:]
                  elif str[0] == '-':
                      flag = -1
                      str = str[1:]
                  if len(str) == 0:
                      return 0
                  
                  i = 0
                  res = 0
                  while i<len(str):
                      try:
                          res = flag*int(str[:i+1])
                          i += 1
                      except:
                          break
              
                  if res>0:
                      return min(res,2**31-1)
                  else:
                      return max(res,-2**31)
                 
              else:
                  return 0

      通过

  7. 实现 strStr()

    1. 实现 strStr() 函数。

      给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1

    2. class Solution:
          def strStr(self, haystack: str, needle: str) -> int:
              if needle == '':
                  return 0
              i = 0
              while i < len(haystack):
                  while i < len(haystack) and haystack[i] != needle[0]:
                      i += 1
                  if i == len(haystack):
                      return -1
                  res = i
                  
                  j = 0
                  while j < len(needle) and i < len(haystack) and haystack[i]==needle[j]:
                      j += 1
                      i += 1
                  if j == len(needle):
                      return res
                  if i == len(haystack):
                      return -1
                  i  = res + 1
              return -1

      通过

  8. 外观数列

    1. 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下:

      1.     1
      2.     11
      3.     21
      4.     1211
      5.     111221
    2. class Solution:
          def countAndSay(self, n: int) -> str:
              dic = {1:"1"}
              if n==1:
                  return "1"
              else:
                  if n-1 in dic:
                      tmp_n_1 = dic[n-1]
                  else:
                      tmp_n_1 = self.countAndSay(n-1)
                      dic[n-1] = tmp_n_1
                  res = ['1',tmp_n_1[0]]
                  for i in range(1,len(tmp_n_1)):
                      if tmp_n_1[i] == res[-1]:
                          res[-2] = str(1+int(res[-2]))
                      else:
                          res.extend(['1',tmp_n_1[i]]) 
                  return ''.join(res)

      通过

  9. 最长公共前缀

    1. 编写一个函数来查找字符串数组中的最长公共前缀。

      如果不存在公共前缀,返回空字符串 ""

    2. class Solution:
          def longestCommonPrefix(self, strs: List[str]) -> str:
              if len(strs) == 0:
                  return ""
              elif len(strs) == 1:
                  return strs[0]
              elif '' in strs:
                  return ''
              p = 0
              while 1:
                  if p < len(strs[0]):
                      tmp = strs[0][:p+1] 
                  else:
                      return tmp
                  for i in range(1,len(strs)):
                      if p < len(strs[i]):
                          tmp1 = strs[i][:p+1]
                          if tmp1 == tmp:
                              continue
                          else:
                              return tmp[:-1]
                      else:
                          return strs[i]
                  p += 1

      通过,但是应该有更优的解法。

发布了45 篇原创文章 · 获赞 1 · 访问量 8562

猜你喜欢

转载自blog.csdn.net/qq_32110859/article/details/104868420