mirror of
https://gitlab.com/game-loader/hugo.git
synced 2025-04-20 05:52:07 +08:00
leetcode content
This commit is contained in:
parent
2f90bd5ed1
commit
943c8ec9d4
@ -207,3 +207,61 @@ func isEvenOddTree(root *TreeNode) bool {
|
|||||||
go语言中的for range循环, 如果使用类似`for key, value := range list` 的形式, 那么key, value这两个变量都会在当前作用域下新建, 意味着即使在前面定义了key, key的值在循环结束后也不会被修改. 若想修改之前定义的key值, 需要将value也提前定义好并使用`=`而不是`:=`.
|
go语言中的for range循环, 如果使用类似`for key, value := range list` 的形式, 那么key, value这两个变量都会在当前作用域下新建, 意味着即使在前面定义了key, key的值在循环结束后也不会被修改. 若想修改之前定义的key值, 需要将value也提前定义好并使用`=`而不是`:=`.
|
||||||
|
|
||||||
go语言中的for range循环时如果使用`:=`会新建两个变量, 然后将slice中的值复制给value变量, 将对应的index值赋值给key变量, 这意味着value变量不会指向数组中对应位置的地址, 而是一个不变的单独地址.
|
go语言中的for range循环时如果使用`:=`会新建两个变量, 然后将slice中的值复制给value变量, 将对应的index值赋值给key变量, 这意味着value变量不会指向数组中对应位置的地址, 而是一个不变的单独地址.
|
||||||
|
|
||||||
|
## day4 2024-03-01
|
||||||
|
|
||||||
|
### 2864. Maximum Odd Binary number
|
||||||
|
|
||||||
|
You are given a binary string s that contains at least one '1'.
|
||||||
|
|
||||||
|
You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.
|
||||||
|
|
||||||
|
Return a string representing the maximum odd binary number that can be created from the given combination.
|
||||||
|
|
||||||
|
Note that the resulting string can have leading zeros.
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
> Input: s = "010"
|
||||||
|
> Output: "001"
|
||||||
|
> Explanation: Because there is just one '1', it must be in the last position. So the answer is "001".
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
> Input: s = "0101"
|
||||||
|
> Output: "1001"
|
||||||
|
> Explanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001".
|
||||||
|
|
||||||
|
### 题解
|
||||||
|
|
||||||
|
题目中说明了给出的字符串中至少有一个1, 因此可以复制一个字符串, 然后遍历原字符串, 遇到第一个1放在最后一位, 0永远插入到倒数第二位, 不是第一个1放在字符串最前面. 由此除保证字符串是奇数的最后一个1以外, 其余的1都在字符串最前面, 其余的0都插入在最前面的一串1和最后的1之间. 保证了字符串是最大的奇数字符串.
|
||||||
|
|
||||||
|
### 代码
|
||||||
|
|
||||||
|
```go
|
||||||
|
func maximumOddBinaryNumber(s string) string {
|
||||||
|
s_copy := ""
|
||||||
|
flag := 0
|
||||||
|
for _, value := range s{
|
||||||
|
if value == '1'{
|
||||||
|
if flag != 0{
|
||||||
|
s_copy = "1" + s_copy
|
||||||
|
} else{
|
||||||
|
s_copy = s_copy + "1"
|
||||||
|
flag = 1
|
||||||
|
}
|
||||||
|
} else{
|
||||||
|
if(len(s_copy) >=2){
|
||||||
|
s_copy = string(s_copy[:len(s_copy)-1]) + "0" + string(s_copy[len(s_copy)-1])
|
||||||
|
} else {
|
||||||
|
s_copy = "0" + s_copy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s_copy
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 总结
|
||||||
|
|
||||||
|
在处理字符串的时候像中间某个位置插入字符也要使用双引号, 如插入字符0要用`+"0"`而不是`+'0'`, 此外在截取切片的时候go的切片是左闭右开的. 如[0:3]截取的是0,1,2三个数
|
||||||
|
Loading…
Reference in New Issue
Block a user