使用 Go 解決 LeetCode 問題:125. Valid Palindrome

Description

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

  • Note:

For the purpose of this problem, we define empty string as valid palindrome.

  • Example 1:
1
2
Input: "A man, a plan, a canal: Panama"
Output: true
  • Example 2:
1
2
Input: "race a car"
Output: false

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func isPalindrome(s string) bool {
arr := []rune{}

for _, b := range s {
// 排除標點符號
if (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') {
arr = append(arr, b)
}
}

for i := 0; i < len(arr)/2; i++ {
diff := arr[i] - arr[len(arr)-i-1]

// 判斷元素是否相同
if diff == 0 {
continue
}

// 判斷字母是否相同(忽略大小寫)
if arr[i] > '9' && diff != 32 && diff != -32 {
return false
}

// 判斷數字是否相同
if arr[i] <= '9' && diff != 0 {
return false
}
}

return true
}

Note

假設有以下參數:

1
s: "A man, a plan, a canal: Panama"

說明:

1
2
3
4
5
6
7
排除標點符號,只將數字和字母的位元組放進陣列中。

此時 arr 為 [65 109 97 110 97 112 108 97 110 97 99 97 110 97 108 80 97 110 97 109 97]。

再判斷陣列中的元素是否對稱。

最終返回:true

Code