携程03.07笔试前两题 Go语言
很少有go语言的代码,哭
(好像是春招笔试,不知道和暑期是否一样
题目链接:https://mp.weixin.qq.com/s/5dOkeepCP-PXt1QXRYGX5Q
第一题:稳定数组
dp
package main import "fmt" func do(nums []int) int { dp := make([]int, len(nums)) for i := range dp { dp[i] = 1 } res := 1 for i := 1; i < len(nums); i++ { if abs(nums[i]-nums[i-1]) <= 1 { dp[i] = max(dp[i-1]+1, dp[i]) } res = max(res, dp[i]) } return res } func abs(a int) int { if a < 0 { return -a } return a } func max(a, b int) int { if a > b { return a } return b } func main() { // var n int // fmt.Scan(&n) // a := make([]int, n) // for i := 0; i < n; i++ { // fmt.Scan(&a[i]) // } a := []int{2, 4, 2, 3, 2} fmt.Println(do(a)) }
第二题:字符串处理
package main import "fmt" func do(s string, left, right int) string { tmp := []byte{} for i := 0; i < len(s); i++ { tmp = append(tmp, s[i]) if i >= left-1 && i <= right-1 { tmp = append(tmp, s[i]) } } return string(tmp) } func main() { // var n int // fmt.Scan(&n) // a := make([]int, n) // for i := 0; i < n; i++ { // fmt.Scan(&a[i]) // } s := "abcdef" cnt := 2 var left, right int for i := 0; i < cnt; i++ { fmt.Scan(&left, &right) s = do(s, left, right) fmt.Println(s) } }#暑期实习笔试#