dpxf81245 2018-08-17 17:36
浏览 53
已采纳

将字符串转换为字母数字[关闭]

I want to find if there is a better way to convert a given string to alpha numeric than to go by ascii value range as I am doing in the following code. It works as expected but wondering if there is a cleaner way to do this.

Also my function buildAlphaN() converts string to lowercase to do the checks that follow.

if input: "A man, a plan, a canal: Panama" then output from buildAlphaN(): amanaplanacanalpanama

I have the whole solution for the problem for context, but my question is purely for the buildAlphaN() function.

// spaces part of palindrome? - ignored. 
import "strings"

//builds alphan and returns lower case
func buildAlphaN(s string) string {
    res := ""
    for _, v := range s {
         //0-9, A-Z, a-z
        if (v >= 48 && v <=57) || (v >= 65 && v <= 90) || (v >= 97 && v <= 122) {
            res += string(v)
        } 
    } 

    return strings.ToLower(res) 
}

func isPalindrome(s string) bool {
    if len(s) == 0 {
        //empty string
        return true
    } 

    s2 := buildAlphaN(s)
    fmt.Printf("s:%v s2:%v
", s, s2)

    if palindromeCheck(s2) == true {
        return true
    }
    return false 
}

func  palindromeCheck(s string) bool {
    if len(s) == 1 {
        return true
    }

    for i, j := 0, len(s) - 1; i < j; i,j = i+1, j-1 {
        if s[i] == s[j] {
            continue
        } else {
            return false 
        } 
    }  
    return true
}
  • 写回答

1条回答 默认 最新

  • duanchifo2866 2018-08-17 18:45
    关注

    For example,

    package main
    
    import (
        "fmt"
        "unicode"
    )
    
    func isPalindrome(s string) bool {
        rs := make([]rune, 0, len(s))
        for _, r := range s {
            if unicode.IsLetter(r) || unicode.IsNumber(r) {
                rs = append(rs, unicode.ToLower(r))
            }
        }
    
        for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
            if rs[i] != rs[j] {
                return false
            }
        }
        return true
    }
    
    func main() {
        s := "A man, a plan, a canal: Panama"
        fmt.Println(isPalindrome(s))
    }
    

    Output:

    true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序