问题
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
分析
话不多说,撸起袖子就是干,双指针解决问题,一个从头遍历,一个从尾遍历,遇到非字符数字的就跳过。golang中没有char类型,golang里字符是用的byte,而byte只是uint8的别名,如官方文档所说。所以可以根据ASCII码表,直接过滤掉其他字符。48-57对应的是十进制0-9,65-90对应的是A-Z,97-122对应的是a-z。
// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention,
// to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8
解法:
func isPalindrome(s string) bool {
i, j := 0, len(s)-1
for i < j {
if !isNumChar(s[i]) {
i++
continue
}
if !isNumChar(s[j]) {
j--
continue
}
if toUpper(s[i]) == toUpper(s[j]) {
i++
j--
} else {
return false
}
}
return true
}
func isNumChar(c uint8) bool {
if (c >= 48 && c<=57) || (c>=65 && c<=90) || (c>=97&& c<=122){
return true
}
return false
}
func toUpper(c uint8) uint8{
// 减少一次比较,只有字符过来,所以大于97就是小写的了,
// 减少这一次比较后,从原先的4ms到0ms了,哈哈哈,在提交就是4ms了,服务器有问题。
if c>=97 { // && c<=122
return c - 32
}
return c
}