LeetCode Weekly Contest 21

523. Continuous Subarray Sum

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.app

Example 1:
Input: [23, 2, 4, 6, 7], k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
Example 2:
Input: [23, 2, 6, 4, 7], k=6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.
Note:
The length of the array won't exceed 10,000.
You may assume the sum of all the numbers is in the range of a signed 32-bit integer.code

Can use Sum[n] = (a[0]+...a[n]) to reduce the time complexity
Payattention to the module K, border checkorm

func checkSubarraySum(nums []int, k int) bool {
    sum := make([]int, 0, len(nums))
    sum = append(sum, 0)
    for index, num := range nums {
        if 0 == index {
            sum = append(sum, num)
        } else {
            sum = append(sum, sum[len(sum)-1] + num)
        }
    }
    
    //fmt.Printf("%v\n", sum)
    sumLen := len(sum)
    for beg:= 0; beg < sumLen; beg++ {
        for end:= beg+2; end < sumLen; end++ {
            if k == 0 {
                if sum[end] - sum[beg] == 0 {
                    return true
                }
            } else {
                if (sum[end] - sum[beg]) % k == 0 {
                    return true
                }
            }
        }  
    }
    
    return false
}

524. Longest Word in Dictionary through Deleting

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.ip

Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]leetcode

Output:
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]get

Output:
"a"
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won't exceed 1,000.
The length of all the strings in the input won't exceed 1,000.input

func match(s, t string) bool {
    ti := 0
    for si := 0; si < len(s); si++ {
        if t[ti] == s[si] {
            ti++
            if ti == len(t) {
                return true
            }
        }
    }
    
    return false
}


func findLongestWord(s string, d []string) string {
    res := ""

    //fmt.Printf("%v\n", "aaaa" > "aaab")

    for _, t := range d {
        if len(t) >= len(res) {
            if true == match(s, t) {
                if len(t) == len(res) && t > res {
                    continue
                }
                res = t
            }
        }
    }    

    return res
}
相關文章
相關標籤/搜索