A straight in playing cards

Topic describes

Draw 5 cards randomly from the playing card to determine whether it is a straight, that is, the 5 cards are not consecutive. A is 1. J is 11. Q is 12. A cannot be considered 14.Copy the code

The sample

Example 1: input: [1,2,3,4,5] output: True example 2: input: [0,0,1,2,5] output: TrueCopy the code

The problem solving

class Solution:
    def isStraight(self, nums: List[int]) -> bool:
        nums.sort()
        zero_count = 0
        for i in range(4):
            if nums[i] == 0:
                zero_count += 1
            elif nums[i] == nums[i + 1]:
                return False
        return nums[4] - nums[zero_count] < 5
Copy the code

This one may seem difficult at first for those who do not play cards. You can actually convert it to, you know, giving you five random numbers to see if it’s a straight, like 12345. And then if you have any of these 0’s, you can view it as any number, there are at most two of them.

The key points of this question are:

  • We know the number of zeros
  • Check if there are duplicate numbers other than 0, if so, return False
  • And the key thing is, again, when the highest number minus the lowest number is always less than 5

Implement strStr()

Topic describes

Implement the strStr() function. Given two strings haystack and needle, find the first place in the haystack string where needle appears (the subscript starts at 0). If none exists, -1 is returned. Description: What value should we return when needle is an empty string? This is a good question to ask in an interview. For this case, we should return 0 when needle is an empty string. This is consistent with the C language STRSTR () and the Java definition of indexOf().Copy the code

The sample

Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaAAA ", needle = "bba" Output: -1 Example 3: Input: Haystack = "", needle = "" output: 0Copy the code

The problem solving

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        m = len(haystack)
        n = len(needle)
        if n == 0:
            return 0
        for i in range(m):
            if haystack[i:i+n] == needle:
                return i
        return -1
Copy the code

Just brute force it. For example, if haystack=”hello”,needle=”ll”, we know that needle is 2, so we loop for hello and see if needle is equal to 2. Notice the empty string.

Verify palindrome string

Topic describes

Given a string, verify that it is a palindrome string, considering only alphanumeric characters, regardless of letter case. Note: In this case, we define an empty string as a valid palindrome string.Copy the code

The sample

Example 1: Enter "A man, A plan, A canal: Panama" Output: true Example 2: enter "race A car" Output: falseCopy the code

The problem solving

class Solution:
    def isPalindrome(self, s: str) -> bool:
        if s == "":
            return True
        temp_list = []
        for i in s:
            if i.isdigit():
                temp_list.append(i)
            if i.isalpha():
                temp_list.append(i.lower())
        return temp_list == temp_list[::-1]
Copy the code

The idea is to determine if the input string is equal to its reverse order, but the question gives other cases to consider:

  • Only alphanumeric characters are considered
  • You can ignore the case of letters
  • An empty string is defined as a valid palindrome string

You can go through the string, and then you can put the characters in the list, and notice what happens when you equal the letters, all lowercase, and then the reverse of the list.

String addition

Topic describes

Given two non-negative integers num1 and num2 in the form of strings, compute their sum.Copy the code

The sample

Tip: both num1 and num2 are less than 5100 in length. Both num1 and num2 contain only the numbers 0-9. Neither num1 nor num2 contain any leading zerosCopy the code

The problem solving

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        cur1 = len(num1) - 1
        cur2 = len(num2) - 1
        carry = 0
        res = ""

        while cur1 >= 0 or cur2 >= 0:
            if cur1 >= 0:
                n1 = int(num1[cur1])
            else:
                n1 = 0
            if cur2 >= 0:
                n2 = int(num2[cur2])
            else:
                n2 = 0
            temp = n1 + n2 + carry
            carry = temp // 10
            res = str(temp % 10) + res
            cur1 -= 1
            cur2 -= 1
        if carry:
            return "1" + res
        else:
            return res
Copy the code

Realize the vertical addition process.

11 // Enter 1 + 123 // enter 2Copy the code
  • Starting from the ones bit to the left, we define two Pointers to each end of the two input strings.
  • Add the two numbers and advance 1 for every 10. Define variablescarryIndicates whether to advance 1, initialize to 0, and pass through the loopcarry = temp // 10

    The assignment.
  • The sum of temporary sumstempIs equal to then1 + n2 + carryNotice hereN1, n2,Traversal is a string to useint()Turn down,

    Can withcarryAdd.
  • Initializes null charactersres = ""Divide each sum by 10 and add the remainder to the front of the res.res = str(temp % 10) + res
  • After each loop, the two Pointers are -1, i.e., move 1 to the left.
  • When either of the two Pointers is less than 0, the current index value is 0 for easy calculation.
  • Until both Pointers are less than 0 and the loop is broken.
  • At this point, if carry! Lambda equals 0, which means we’re going to have to add 1,"1" + resOtherwise, return directlyres.

Five, move zero

Topic describes

Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.Copy the code

The sample

Example: input: [0,1,0,3,12] output: [1,3,12,0,0] note: you must operate on the original array and cannot copy additional arrays. Minimize the number of operations.Copy the code

The problem solving

class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) right = left = 0 while right < n: if nums[right] ! = 0: nums[right], nums[left] = nums[left], nums[right] left += 1 right += 1Copy the code

Can only move in place, consider using double Pointers right and left, such as [0,1,0,3,12] :

  • Initialize theright = left = 0.
  • rightKeep moving to the right, and find something that’s not zero, and then followleftThe element in the.
  • After switching places,leftWe go 1 to the right.