中心扩展+双指针算法获取回文串

ByWhat'sUs

中心扩展+双指针算法获取回文串

找回文数,中心扩展法,枚举每一个可能的回文中心,然后用两个指针分别向左右两边拓展
package main

import (
    "fmt"
)

// handleStr ...
func handleStr(str string) (ant []string) {
    length := len(str)

    // 找回文数,中心扩展法,枚举每一个可能的回文中心,然后用两个指针分别向左右两边拓展
    for i := 0; i < 2*length-1; i++ {
	left, right := i/2, i/2+i%2
	for left >= 0 && right < length && str[left] == str[right] {
	    ant = append(ant, str[left:right+1])
	    left--
	    right++
	}
    }

    ant = removeDuplicateElement(ant)

    return
}

// removeDuplicateElement ...
func removeDuplicateElement(element []string) []string {
    result := make([]string, 0, len(element))
    temp := map[string]struct{}{}
    for _, item := range element {
	if _, ok := temp[item]; !ok {
	    temp[item] = struct{}{}
	    result = append(result, item)
	}
    }

    return result
}

func main() {
    fmt.Println(handleStr("abchcba"))
}

About the author

What'sUs administrator

Leave a Reply

PHP Code Snippets Powered By : XYZScripts.com