Sword finger offer (python) -- string class

Keywords: Python Google

01 replace space

Please implement a function to replace the space in a string with "% 20". For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.

Idea 1: directly use python's own replace function, replace (to replace, substitute)

class Solution:     # s source string
    def replaceSpace(self, s):
        s = s.replace(' ','%20')
        return s
    
if __name__=='__main__':
    s = Solution()
    print(s.replaceSpace('We Are Happy'))

Method 2: replace the space of length 1 with "% 20" of length 3, and the length of string becomes longer. If we can create a new array to store the string after the replacement space,
Then the question is very simple. Set two pointers to point to the first element of the new and old string respectively, traverse the original string, and fill in "% 20" on the new string if a space is encountered,
Otherwise, the contents of the meta string are copied. But if the interviewer asks to operate on the original string and ensures that the original string has enough space to store the replaced string,

Then we have to think of another way. First, traverse the original string to find the length of the string and the number of spaces in it,
According to the length of the original string and the number of spaces, we can find the length of the last new string.
Set two pointers point1 and point2 to point to the end of the original string and the new string respectively.
(why start traversal at the end instead of at the beginning is to use the judgment condition point1poin2)
If point1 points to content that is not a space, assign the content to the location pointed to by point2,
If point1 points to a space, the assignment of "02%" from point2 to point1poin2 indicates that all spaces in the string have been replaced.
Original: https://blog.csdn.net/Yeoman92/article/details/77865878

class Solution:
    def replaceSpace(self, oldString):
        blankNumber = 0#Number of spaces
        oldStringLen = len(oldString)#Length of original string

        #Traverse the original string to find the number of spaces in the string
        for i in range(oldStringLen):
            if oldString[i] == ' ':
                blankNumber += 1

        #Calculate the length of the new string
        newStringLen = oldStringLen + blankNumber * 2
        #Declare a new string list (because strings are immutable)
        newStringList = [' '] * newStringLen

        #Set two pointers to the end of the original string and the new string
        point1 = oldStringLen - 1
        point2 = newStringLen - 1

        #Ergodic substitution
        while point1 != point2:#If the two pointer positions are different, the replacement is not completed
            if oldString[point1] != ' ':#Character is not empty
                newStringList[point2] = oldString[point1]
                point1 -= 1
                point2 -= 1
            else:
                newStringList[point2] = '0'
                newStringList[point2-1] = '2'
                newStringList[point2-2] = '%'
                point1 -= 1
                point2 -= 3

        #When the pointer is exactly the same, the previous characters are filled in
        if point1 > 0:
            for i in range(point1,-1,-1):
                newStringList[i] = oldString[i]

        #Combine string arrays into strings
        newString = ''
        for i in range(newStringLen):
            newString += str(newStringList[i])

        return newString

#test case
s = Solution()
print(s.replaceSpace('We Are Happy'))

02 regular expression matching

Title Description
Please implement a function to match regular expressions including '.' and '. The character in the pattern '.' represents any character, and 'represents that the character before it can appear any number of times (including 0 times). In this problem, matching means that all characters of a string match the whole pattern. For example, the string "a a a" matches the patterns "a.a" and "abaca", but not "aa.a" and "ab*a"

Train of thought 1 - match directly one condition one condition

# -*- coding:utf-8 -*-
class Solution:
    # s. Patterns are strings
    def match(self, s, pattern):
        # True if s and pattern are both empty
        if len(s) == 0 and len(pattern) == 0:
            return True
        # False if s is not empty and pattern is empty
        elif len(s) != 0 and len(pattern) == 0:
            return False
        # If s is empty and pattern is not empty, judgment is required
        elif len(s) == 0 and len(pattern) != 0:
            # If the second character in the pattern is *, the pattern will be moved back two bits to continue the comparison
            if len(pattern) > 1 and pattern[1] == '*':
                return self.match(s, pattern[2:])
            else:
                return False
        # When s and pattern are not empty
        else:
            # When the second character of the pattern is *
            if len(pattern) > 1 and pattern[1] == '*':
                # If s is different from the first element of pattern, then s will not change, and pattern will move two bits backward, which is equivalent to that the first two bits of pattern are empty
                if s[0] != pattern[0] and pattern[0] != '.':
                    return self.match(s, pattern[2:])
                else:
                    # If s[0] is the same as pattern[0], and pattern[1] is *, there are three situations
                    # The pattern is moved back 2 times, and s remains the same; it is equivalent to taking the first two bits of pattern as empty and matching the following
                    # Two pattern s are moved backward and one is moved backward by s, which is equivalent to matching the first two bits of pattern with s[0]
                    # If the pattern is unchanged, s moves backward by one; it is equivalent to the first two bits of the pattern, matching with many bits in s, because * can match many bits
                    return self.match(s, pattern[2:]) or self.match(s[1:], pattern[2:]) or self.match(s[1:], pattern)
            # When the second character of pattern is not *
            else:
                if s[0] == pattern[0] or pattern[0] == '.':
                    return self.match(s[1:], pattern[1:])
                else:
                    return False

03 - string representing the value

Title Description
Implement a function to determine whether a string represents a number, including integers and decimals. For example, the strings "+ 100", "5e2", "- 123", "3.1416" and "- 1E-16" all represent numeric values. But "12e", "1a3.14", "1.2.3", "± 5" and "12e+4.3" are not.

Train of thought 1 - direct condition by condition experiment

# -*- coding:utf-8 -*-
class Solution:
    # s String
    def isNumeric(self, s):
        # write code here
        if s is None or len(s) == 0:
            return False

        # Do you have e?
        hasE = False
        # Whether there is decimal
        isDecimal = False
        # Is there a + - sign
        hasSign = False

        for i in range(len(s)):
            # If there is an e, there can only be one e and not the last one
            if s[i] == "e" or s[i] == "E":
                if hasE or i == len(s) - 1:
                    return False
                hasE = True
            # Decimal point cannot be repeated or collinear with e
            elif s[i] == ".":
                if hasE or isDecimal:
                    return False
                isDecimal = True
            elif s[i] == "-" or s[i] == "+":
                # When a symbol appears repeatedly, it must be followed by e
                if hasSign and s[i - 1] != "e" and s[i - 1] != "E":
                    return False
                # When a symbol appears repeatedly, it must be followed by e
                if not hasSign and i > 0 and s[i - 1] != "e" and s[i - 1] != "E":
                    return False
                hasSign = True
            elif s[i] < "0" or s[i] > "9":
                return False
        return True

04 - the first non repeating character in the character stream

Please implement a function to find the first character in the character stream that only appears once. For example, when only the first two characters "go" are read from a character stream, the first character that appears only once is "g". When the first six characters "google" are read from the stream, the first character that appears only once is "l".

Idea 1 - directly use count function for calculation

# -*- coding:utf-8 -*-
class Solution:
    # Return corresponding char
    def __init__(self):
        self.c=""
    def FirstAppearingOnce(self):
        for s in self.c:
            if self.c.count(s)==1:
                return s
        return "#"
    def Insert(self, char):
        self.c=self.c+(char)

Only when the first parameter of a method in a class is self can it be called by an instance.
The parameters with self in the class are instance parameters, and the instance has the ownership of this parameter, that is, all methods in the instance can use the instance parameters.
As for the parameter when to add self and when not to add self, I think you just need to make clear what role self plays, and this problem will not be self-evident.

61 original articles published, 10 praised, 20000 visitors+
Private letter follow

Posted by dlester on Wed, 26 Feb 2020 23:18:28 -0800