golang刷题与打卡笔记

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
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

submarineas

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值