[golang] leetcode Beginner - verify palindrome string & string conversion integer

Posted by Z3RatuL on Sat, 22 Jan 2022 13:03:20 +0100

Question 1 verify palindrome string

Topic information

Given a string, verify whether it is a palindrome string. Only alphanumeric characters are considered, and the case of letters can be ignored.

Note: in this topic, we define an empty string as a valid palindrome string.

 

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true
Explanation: "Amana planacanalpanama" is a palindrome string
Example 2:

Enter: "race a car"
Output: false
Explanation: "raceacar" is not a palindrome string
 

Tips:

1 <= s.length <= 2 * 105
The string s consists of ASCII characters

Problem solving ideas

According to the example, it is obvious that before verifying whether it is a palindrome string, due to

Only alphabetic and numeric characters are considered, and the case of letters can be ignored

So for a given string, we should

Extract the part of the string that belongs to characters and numbers
 Ignore remaining symbols

Then we just need to verify whether the extracted string is a palindrome string

code

func isPalindrome(s string) bool {
    if len(s)==1{
        return true
    }
    var ss []byte
    for i, n := range s {
        if n <= 'Z' && n >= 'A' {
            ss = append(ss, s[i]+32)
        }
        if n >= 'a' && n <= 'z' || n >= '0' && n <= '9' {
            ss = append(ss, s[i])
        }
    }
    if ss==nil {return true}
    for i := 0; i <= len(ss)/2; i++ {
        if ss[i] != ss[len(ss)-i-1] {
            return false
        }
    }
    return true
}

Complexity analysis

Time complexity: O(∣ s ∣), where ∣ s ∣ is the length of string ss.

Spatial complexity: O(∣ s ∣). Because we need to store all alphabetic and numeric characters in another string, in the worst case, the new string is exactly the same as the original string s, so we need to use O(∣ s ∣) space.

optimization

Learn from the second method of official analysis
You can use double pointers to operate directly on the original array to optimize the space complexity to a constant level
The code is as follows

func isPalindrome(s string) bool {
    s = strings.ToLower(s)
    left, right := 0, len(s) - 1
    for left < right {
        for left < right && !isalnum(s[left]) {
            left++
        }
        for left < right && !isalnum(s[right]) {
            right--
        }
        if left < right {
            if s[left] != s[right] {
                return false
            }
            left++
            right--
        }
    }
    return true
}

func isalnum(ch byte) bool {
    return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')
}

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

Second question

Topic information

Please implement a myAtoi(string s) function to convert a string into a 32-bit signed integer (similar to the atoi function in C/C + +).

The algorithm of the function myAtoi(string s) is as follows:

Read in the string and discard useless leading spaces
Check whether the next character (assuming it has not reached the end of the character) is a positive or negative sign, and read the character (if any). Determines whether the final result is negative or positive. If neither exists, the result is assumed to be positive.
Read the next character until you reach the next non numeric character or the end of the input. The rest of the string will be ignored.
Convert these numbers read in the previous steps into integers (i.e., "123" - > 123, "0032" - > 32). If no number is read in, the integer is 0. Change the symbol if necessary (starting from step 2).
If the number of integers exceeds the range of 32-bit signed integers [− 231, 231 − 1], the integer needs to be truncated to keep it within this range. Specifically, integers less than − 231 should be fixed as − 231, and integers greater than 231 − 1 should be fixed as 231 − 1.
Returns an integer as the final result.
be careful:

The white space character in this question only includes the white space character ''.
Do not ignore any characters other than the leading space or the rest of the string after the number.

Problem solving ideas

1. The leading space needs to be removed;
2. It is necessary to judge whether the first character is + and -. Therefore, a variable sign can be designed, which is 1 during initialization. If -, the sign can be corrected to - 1;
3. To judge whether it is a number, the ASCII code value of the character can be used for comparison, i.e. 0 < = C < = '9';
4. When the first character that is not a number is encountered, the conversion stops and exits the cycle;
5. If the converted number exceeds the range of int type, it needs to be intercepted.

code

func myAtoi(s string) int {
    num, sign, i, n := 0, 1, 0, len(s)

    for i < n && s[i] == ' ' {
        i++
    }

    if i < n {
        if s[i] == '-' {
            sign = -1
            i++
        } else if s[i] == '+' {
            sign = 1
            i++
        }
    }
    for i < n && s[i] >= '0' && s[i] <= '9' {
        num = 10*num + int(s[i]-'0')  
        if sign*num < math.MinInt32 { 
            return math.MinInt32
        } else if sign*num > math.MaxInt32 {
            return math.MaxInt32
        }
        i++
    }
    return sign * num
}

Complexity analysis

Time complexity: O (n)
Space complexity: O (1)

Topics: Go