寻找最长公共前缀
2019獨角獸企業重金招聘Python工程師標準>>>
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
給定一個string數組,尋找公共的最長前綴;
假設給定數組 ab, ac, ad, 那么最長公共前綴為a
基本思路:
1. 切分出每個字符串的所有前綴,比如abc的前綴為, "", a, ab, abc;?
2. 將這些前綴連接成一個新的前綴數組;對于給定的例子, 可以得到,["", a, ab, "", a, ac, "", a, ad]的前綴數組;
3. 那么公共的前綴的,其數量必然等于輸入字符數組的總和n;比如 "" 肯定是一個公共前綴,那么在前綴數組總, 必然包含n個 "";
接下來的問題是怎么找到最長的公共前綴;
最簡單的方法先排序,然后依次掃描前綴, 并計數;直到找到一個計數少于n的前綴,那么前一個就是最長公共前綴;
但如果排過序了, 其實可以用二分查找的方式更快的找到答案;下面是二分查找的代碼:
package mainimport ("fmt""sort" )func main() {strs := []string{"flower", "flow", "flight"}fmt.Printf("%s\n", longestCommonPrefix(strs)) }func longestCommonPrefix(strs []string) string {if len(strs) == 0 {return ""}prefix := make([]string, 0, len(strs))for _, str := range strs {prefix = appendStrPrefix(prefix, str)}sort.Strings(prefix)return findCommonPrefix(prefix, len(strs)) }func findCommonPrefix(pres []string, n int) string {i, j := 0, len(pres)-1for i <= j {m := (i + j) / 2c := countOfPreAt(pres, m)if c == n {i = m + 1} else {j = m - 1}}return pres[i-1] }func countOfPreAt(pres []string, p int) int {s := pres[p]i := pfor i >= 0 && pres[i] == s {i--}j := pfor j < len(pres) && pres[j] == s {j++}return (j - 1) - (i + 1) + 1 }func appendStrPrefix(pre []string, str string) []string {for i := 0; i <= len(str); i++ {pre = appendMore(pre, str[:i])}return pre }func appendMore(strs []string, str string) []string {if len(strs)+1 == cap(strs) {tmp := make([]string, len(strs), 2*cap(strs))copy(tmp, strs)strs = tmp}return append(strs, str) }?
轉載于:https://my.oschina.net/u/922297/blog/700126
總結
- 上一篇: android通过BitmapFacto
- 下一篇: idea控制台输出乱码