LeetCode 014&053

xiaoyusilen發表於2019-01-23

最近在刷 LeetCode,今天順手總結兩道題目的題解~

14. Longest Common Prefix

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 "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
複製程式碼

Example 2:

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.

簡單的說就是求最長公共字首,解法的思路如圖,

image-20180708134936170

就是每兩個字串進行對比,尋找最大的字首,然後找到的字首與下一個字串進行字首匹配,當然也可以先把字串根據長度排序,用最短的那個字串作為最開始的字首來進行匹配查詢,因為最長公共字首的長度不會超過最短的字串長度~

Solution

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))
}
複製程式碼

53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

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`s algorithm

簡單來說,kadane 演算法就是,當 index = i 時,

  • 如果 sum(a[0:i]) < 0,那麼就取 a[i] 作為 sum
  • 如果 sum(a[0:i]) > 0,那麼就取 sum + a[i] 作為sum

同時,還存在一個變數來記錄過程中有過的最大值,因為 sum + a[i],其中 a[i] 有可能是負數,如果以 sum 作為結果,可能就無法獲取到最大的和,思想其實就是 DP 的思想啦~

狀態轉移方程就是,

sum = max(a[i], sum+a[i])
max = max(sum, max)
複製程式碼

Solution

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))
}
複製程式碼