算法练习Day7 (Leetcode/Python-字符串)

替换数字

卡码网题目链接(opens new window)

给定一个字符串 s,它包含小写字母和数字字符,请编写一个函数,将字符串中的字母字符保持不变,而将每个数字字符替换为number。

例如,对于输入字符串 "a1b2c3",函数应该将其转换为 "anumberbnumbercnumber"。

对于输入字符串 "a5b",函数应该将其转换为 "anumberb"

输入:一个字符串 s,s 仅包含小写字母和数字字符。

输出:打印一个新的字符串,其中每个数字字符都被替换为了number

样例输入:a1b2c3

样例输出:anumberbnumbercnumber

数据范围:1 <= s.length < 10000。

思路: From 代码随想录

其实很多数组填充类的问题,其做法都是先预先给数组扩容带填充后的大小,然后在从后向前进行操作。

这么做有两个好处:

  1. 不用申请新数组。
  2. 从后向前填充元素,避免了从前向后填充元素时,每次添加元素都要将添加元素之后的所有元素向后移动的问题。

注意!python里不能对string直接用s[i] 赋值,转成了list实现以上思想,最后记得再把list转成str。

def inplace(s:str):
        count = 0  # Count the number of digits
        s_old_size = len(s)
        
        for char in s:
            if '0' <= char <= '9':
                count += 1

        # Resize the string s, i.e., the size after replacing each space with "number"
        s += ' ' * (count * 5)
        s_new_size = len(s)

        s = list(s)

        # Replace spaces with "number" from the end to the beginning
        i, j = s_new_size - 1, s_old_size - 1
        while j < i:
            if not ('0' <= s[j] <= '9'):
                s[i] = s[j]
            else:
                s[i - 5:i+1] = 'number'
                i -= 5
            i -= 1
            j -= 1
        s = "".join(s)
        print(s)

# Time complexity O(n^2)


541. Reverse String II

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Solution:
use sub_s[j], sub_s[i] = sub_s[i], sub_s[j] to reverse.
class Solution(object):
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        def reverse(sub_s):
            i,j = 0, len(sub_s)-1
            while i < j: 
                sub_s[j], sub_s[i] = sub_s[i], sub_s[j]
                i += 1
                j -= 1

            return sub_s

        res = list(s)
        for i in range(0, len(s), 2*k):
            res[i:i+k] = reverse(res[i:i+k])

        res = ''.join(res)
        return res


151. Reverse Words in a String

Given an input string s, reverse the order of the words.

word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

solution: 

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = []
        # initialization 
        s = s.strip() # remove the space at the beginning/on the end 
        left = len(s)-1
        right = len(s)-1
        while left >= 0:
          while left>=0 and  s[left] != ' ':
            left -= 1
          res.append(s[left+1:right+1])
          # remove repeated space 
          while left>=0 and  s[left] == ' ': 
            left -= 1
          right = left 
        return ' '.join(res)

你可能感兴趣的:(leetcode,算法)