2020/12/16 单词规律
题目链接: https://leetcode-cn.com/problems/word-pattern/
创建两个map,一个用来存储规则字符串,一个存储单词字符串,然后对其进行遍历并分别匹配:
func wordPattern(pattern string, s string) (res bool) {
//获取两个字符串数组
wordArr := strings.Split(pattern,"")
word1Arr := strings.Split(s," ")
if len(wordArr) != len(word1Arr){
return
}
//创建两个hashMap用来存储值
wordMap := make(map[string]string)
word1Map := make(map[string]string)
//遍历规则字符串数组1
for key,val := range wordArr{
if sVal , ok := wordMap[val];ok{
//如果map1中存在该值
pVal ,ok1 := word1Map[sVal]
//检查map中对应是否存在该值,不存在则不符合,且word1Map中该值等于遍历到的此时的值,wordMap中该值等于数组word1Arr的值
if !ok1 || pVal != val || sVal != word1Arr[key]{
return
}
}else{
//不存在则加入hashMap
wordMap[val] = word1Arr[key]
//map1不存在,则map2是一一对应 关系则也不能存在
if _,ok := word1Map[word1Arr[key]];ok{
return
}
word1Map[word1Arr[key]] = val
}
}
return true
}
2020/12/21.22:使用最小花费爬楼梯
题目链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs/
python
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
n = len(cost)
minCost = [0] * n
minCost[1] = min(cost[0], cost[1])
for i in range(2, n):
minCost[i] = min(minCost[i - 1] + cost[i], minCost[i - 2] + cost[i - 1])
return minCost[-1]
golang
func minCostClimbingStairs(cost []int) int {
head := 0
next := 0
for i := 2; i <= len(cost); i++ {
a := next+cost[i-1]
b := head+cost[i-2]
if a>b{
head,next = next, b
}else{
head,next = next,a
}
}
return next
}
关于爬楼梯,还有另一个题目同样是用动态规划或者递归来解决:
题目链接:https://leetcode-cn.com/problems/climbing-stairs
func climbStairs(n int) int {
dp := make([]int, n+1)
dp[0] = 1
dp[1] = 1
for i := 2; i < len(dp); i++ {
dp[i] = dp[i-2] + dp[i-1]
}
return dp[n]
}
2020/12/23:
题目链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
func firstUniqChar(s string) int {
fmap := make(map[byte]int)
for i:=0; i<len(s);i++ {
if _,ok :=fmap[s[i]];ok{
fmap[s[i]] += 1
}else {
fmap[s[i]] = 1
}
}
for i:=0; i<len(s);i++ {
nums := fmap[s[i]]
if nums == 1{
return i
}
}
return -1
}