dongpangfu6322 2014-12-13 05:49
浏览 29
已采纳

回文-是否有可能使我的代码更快

I have an ASCII-only string which is either already a palindrome, or else can be made a palindrome by removing one character. I need to determine whether it's already a palindrome, and if not, I need to find the index of the character that would need to be removed. For example, if the string is 'aaba', then it can be made into the palindrome 'aba' by removing the first character, so I need to return 0.

I have working code, but I am wondering if it is possible to make it faster, because I need to work with many long strings.

Here is my code:

package main

import (
    "fmt"
    )

func Palindrome(s string) bool {
    var l int = len(s)

    for i := 0; i < l / 2; i++ {
        if s[i] != s[l - 1 - i] {
            return false;
        }
    }

    return true
}

func RemoveChar(s string, idx int) string {
    return s[0:idx-1] + s[idx:len(s)]
}

func findIdx(s string) int {
    if Palindrome(s) {
        return -1
    }

    for i := 0; i < len(s); i++ {
        if Palindrome(RemoveChar(s, i + 1)) {
            return i
        }
    }

    return -2
}

func main() {
    var s string = "aabaab"
    fmt.Println(findIdx(s))
}
  • 写回答

2条回答 默认 最新

  • dorkahemp972157683 2014-12-13 06:29
    关注

    Here is a much more efficient approach:

    func findIdx(s string) int {
        for i := 0; i < len(s) / 2; i++ {
            if s[i] != s[len(s) - i - 1] {
                 if isPalindrome(s[i+1:len(s)-i]) {
                     return i
                 } else {
                     return len(s) - i - 1
                 }
            }
        }
    
        return -1
    }
    

    It just proceeds from the ends of the string until it finds a pair of bytes that should match, if the string were a palindrome, but that do not. It then knows that it will return the index of one of these two bytes, so it only needs to perform one "is this a palindrome?" check; and it doesn't need to use the RemoveChar function, since the "is this a palindrome?" check only needs to consider the middle portion of the string (that hasn't already been examined).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器