LeetCode - #125 Validate palindrome strings

foreword

Our community will successively organize Gu Yi ( Netflix Growth Hacker, author of "The Way of the iOS Interview", ACE Professional Fitness Coach. )'s Swift algorithm problem solutions into a text version for everyone to learn and read.

We have updated the LeetCode algorithm to 124 issues so far, and we will keep the update time and progress ( released at 9:00 am on Monday, Wednesday, and Friday ). There will be a big improvement.

If you don't accumulate a small step, you can't go a thousand miles; if you don't accumulate a small stream, you can't make a river. The Swift community accompanies you to move forward. If you have suggestions and comments, please leave a message at the end of the article, we will try our best to meet your needs.

Difficulty Level: Easy

1. Description

Given a string, verify that it is a palindrome, considering only alphanumeric characters, ignoring case of letters.

Explanation: In this problem, we define the empty string as a valid palindrome.

2. Example

Example 1

输入: "A man, a plan, a canal: Panama"
输出: true
解释:"amanaplanacanalpanama" 是回文串

Example 2

输入: "race a car"
输出: false
解释:"raceacar" 不是回文串

Restrictions:

  • 1 <= s.length <= 2 * 10^5
  • string sconsisting of ASCII characters

3. Answers

class ValidPalindrome {
    func isPalindrome(_ s: String) -> Bool {
        var i = 0, j = s.count - 1
        let sChars = Array(s.lowercased())
        
        while i < j {
            while !sChars[i].isAlphanumeric && i < j {
                i += 1
            }
            
            while !sChars[j].isAlphanumeric && i < j {
                j -= 1
            }
            
            if sChars[i] != sChars[j] {
                return false
            } else {
                i += 1
                j -= 1
            }
        }
        
        return true
    }
}

extension Character {
    var isValid: Bool {
        return isLetter || isNumber
    }
}
  • Main idea: For each index in the first half of the String, compare the two values ​​at the mirror index. .
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Repository for the algorithm solution: LeetCode-Swift

Click to go to LeetCode practice

about us

We are jointly maintained by Swift enthusiasts. We will share the technical content centered on Swift combat, SwiftUI, and Swift foundation, and also organize and collect excellent learning materials.

Guess you like

Origin juejin.im/post/7121608714314285093