diff --git a/leetcode/101-200/0125.Valid-Palindrome/README.md b/leetcode/101-200/0125.Valid-Palindrome/README.md new file mode 100644 index 000000000..33328ddba --- /dev/null +++ b/leetcode/101-200/0125.Valid-Palindrome/README.md @@ -0,0 +1,38 @@ +# [125.Valid Palindrome][title] + +## Description +A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. + +Given a string `s`, return `true` if it is a **palindrome**, or `false` otherwise. + +**Example 1:** + +``` +Input: s = "A man, a plan, a canal: Panama" +Output: true +Explanation: "amanaplanacanalpanama" is a palindrome. +``` + +**Example 2:** + +``` +Input: s = "race a car" +Output: false +Explanation: "raceacar" is not a palindrome. +``` + +**Example 3:** + +``` +Input: s = " " +Output: true +Explanation: s is an empty string "" after removing non-alphanumeric characters. +Since an empty string reads the same forward and backward, it is a palindrome. +``` + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me] + +[title]: https://leetcode.com/problems/valid-palindrome +[me]: https://github.com/kylesliu/awesome-golang-algorithm diff --git a/leetcode/101-200/0125.Valid-Palindrome/Solution.go b/leetcode/101-200/0125.Valid-Palindrome/Solution.go index d115ccf5e..f0e5edf1e 100644 --- a/leetcode/101-200/0125.Valid-Palindrome/Solution.go +++ b/leetcode/101-200/0125.Valid-Palindrome/Solution.go @@ -1,5 +1,40 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(s string) bool { + var is func(byte) byte + is = func(b byte) byte { + if b >= '0' && b <= '9' { + return b + } + if b >= 'a' && b <= 'z' { + return b + } + if b >= 'A' && b <= 'Z' { + return b + 32 + } + return byte(' ') + } + l, r := 0, len(s)-1 + var bl, br byte + for l < r { + for ; l < r; l++ { + bl = is(s[l]) + if bl != byte(' ') { + break + } + } + for ; l < r; r-- { + br = is(s[r]) + if br != byte(' ') { + break + } + } + if l < r { + if bl != br { + return false + } + l, r = l+1, r-1 + } + } + return true } diff --git a/leetcode/101-200/0125.Valid-Palindrome/Solution_test.go b/leetcode/101-200/0125.Valid-Palindrome/Solution_test.go index 14ff50eb4..fb9a42d04 100644 --- a/leetcode/101-200/0125.Valid-Palindrome/Solution_test.go +++ b/leetcode/101-200/0125.Valid-Palindrome/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool + inputs string expect bool }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", "A man, a plan, a canal: Panama", true}, + {"TestCase2", "race a car", false}, + {"TestCase3", " ", true}, } // 开始测试 @@ -30,10 +30,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }