最近在刷 LeetCode,今天順手總結兩道題目的題解~算法
Write a function to find the longest common prefix string amongst an array of strings.數組
If there is no common prefix, return an empty string
""
.bashExample 1:app
Input: ["flower","flow","flight"] Output: "fl" 複製代碼
Example 2:ide
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. 複製代碼
Note: All given inputs are in lowercase letters
a-z
.ui
簡單的說就是求最長公共前綴,解法的思路如圖,spa
就是每兩個字符串進行對比,尋找最大的前綴,而後找到的前綴與下一個字符串進行前綴匹配,固然也能夠先把字符串根據長度排序,用最短的那個字符串做爲最開始的前綴來進行匹配查找,由於最長公共前綴的長度不會超過最短的字符串長度~code
package main
import (
"fmt"
"strings"
)
func longestCommonPrefix(strs []string) string {
// 若是數組是空的,那麼返回 ""
if(len(strs) == 0) {
return ""
}
// 取第一個字符串做爲初始的前綴
prefix := strs[0]
for i := 1; i < len(strs); i++{
// 這個循環的目的是,根據查找前綴的位置來判斷是否已經找到公共前綴
for ; strings.Index(strs[i], prefix) != 0; {
// 沒找到,則去掉最後一位,繼續嘗試
prefix = prefix[0:len(prefix) - 1]
// 若是沒有公共前綴,就返回 ""
if(len(prefix) == 0) {
return ""
}
}
}
return prefix
}
func main() {
a := []string{"flower", "flow", "flight"}
fmt.Println(longestCommonPrefix(a))
a = []string{"aa", "a"}
fmt.Println(longestCommonPrefix(a))
}
複製代碼
Given an integer array
nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.cdnExample:blog
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. 複製代碼
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
題面如上~簡單的說,就是要求子區間的最大和~O(n) 複雜度的解是使用了 Kadane 算法,這個算法是專門用於求最大子序列的和~
簡單來講,kadane 算法就是,當 index = i 時,
同時,還存在一個變量來記錄過程當中有過的最大值,由於 sum + a[i],其中 a[i] 有多是負數,若是以 sum 做爲結果,可能就沒法獲取到最大的和,思想其實就是 DP 的思想啦~
狀態轉移方程就是,
sum = max(a[i], sum+a[i])
max = max(sum, max)
複製代碼
package main
import (
"fmt"
)
func getMax(a int, b int) int {
if a > b {
return a
}
return b
}
func maxSubArray(nums []int) int {
// 這裏注意須要初始化爲 nums[0] 或者一個極小值,不能初始化爲 0
// bad case: [-1] output: 0
sum, max := nums[0], nums[0]
for i := 1; i < len(nums); i++ {
sum = getMax(nums[i], sum + nums[i])
max = getMax(sum, max)
}
return max
}
func main() {
a := []int{-2,1,-3,4,-1,2,1,-5,4}
fmt.Println(maxSubArray(a))
}
複製代碼