avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

One question daily 2299. Code inspection device II

  2024-01-01
字数统计: 283字   |   阅读时长: 1min

2023-01-20.png

Excess when executing100%User,What can I say about this question,But oneBit operationKnowledge point

My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def strongPasswordCheckerII(self, password: str) -> bool:
flag1 = flag2 = flag3 = flag4 = 1
ret = None
for i in password:
if ret == i:
return False
if i.isdigit():
flag1 = 0
elif i.isupper():
flag2 = 0
elif i.islower():
flag3 = 0
else:
flag4 = 0
ret = i
if sum([flag1, flag2, flag3, flag4]) == 0 and len(password) >= 8:
return True
return False

Bit operation代码:

method one:simulation + Bit operation

According to the description of the topic,我们可以simulation检查密码是否满足题目要求的过程。

first,We check whether the length of the password is less than 8,in the case of,Then return false。

Next,We use a mask mask To record whether the password contains a lowercase letter、uppercase letter、Numbers and special characters。We traverse the password,Like a character every time,First determine whether it is the same as the previous character,in the case of,Then return false。Then,Update mask according to the type of character mask。at last,We check the mask mask Whether it is 15,in the case of,Then return true,否Then return false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def strongPasswordCheckerII(self, password: str) -> bool:
if len(password) < 8:
return False
mask = 0
for i, c in enumerate(password):
if i and c == password[i - 1]:
return False
if c.islower():
mask |= 1
elif c.isupper():
mask |= 2
elif c.isdigit():
mask |= 4
else:
mask |= 8
return mask == 15

author:ylb
Link:https://leetcode.cn/problems/strong-password-checker-ii/solutions/2068878/by-lcbin-hk2a/

  • Python
  • answer
  • Bit operation

show all >>

2309. The best English letters with both appropriates and lowercases One question daily

  2024-01-01
字数统计: 424字   |   阅读时长: 2min

2023-01-27 (3).png
2309. The best English letters with both appropriates and lowercases

Thought:

  1. Hash table:The first thing to think of the question is to solve it with a dictionary。But find that you can directly traverse the alphabet,fromZStart looking for,See if the applause exists,Just return directly。
    9f9081c1d70b0d0e0f736c400e4ddb3.png
    Running time exceeds99.9%
  2. Bit operation:We can use two integers mask1 and mask2 Record string separately s 中出现的小写字母and大写字母,in mask1 First i
    Position representation i Does a lowercase letter appear,and mask2 First i Position representation i Whether an uppercase letter appears。

Then we will mask1 and mask2 Perform and calculate,The results obtained mask First i Position representation i Whether the lethals of the letter appear at the same time。

As long as you get mask The highest level of binary representation 1 s position,Convert it to the corresponding capital letter。If all binary positions are not 1,Explain that there is no letter that appears at the same time,,Return to an empty string。

author:ylb
Link:https://leetcode.cn/problems/greatest-english-letter-in-upper-and-lower-case/solutions/2077636/by-lcbin-zbg0/
source:Deduction(LeetCode)
著作权归author所有。商业转载请联系author获得授权,Non -commercial reprint Please indicate the source。

Code:

Traversing the alphabet
1
2
3
4
5
6
class Solution:
def greatestLetter(self, s: str) -> str:
for i in range(90, 64, -1):
if chr(i) in s and chr(i+32) in s:
return chr(i)
return ""
Hash table
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
string greatestLetter(string s) {
unordered_set<char> strin(s.begin(),s.end());
for(char c = 'Z'; c >= 'A'; --c){
if(strin.count(c) && strin.count(char(c+32))){
return string(1,c);
}
}
return "";
}
};
Bit operation
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def greatestLetter(self, s: str) -> str:
# We can use two integers mask1 and mask2
# Record string separately s 中出现的小写字母and大写字母,in mask1 First i Position representation i Does a lowercase letter appear,
# and mask2 First i Position representation i Whether an uppercase letter appears。
mask1 = mask2 = 0
for i in s:
if i.islower():
mask1 |= 1 << (ord(i) - ord("a"))
else:
mask2 |= 1 << (ord(i) - ord("A"))
mask = mask1 & mask2
return chr(mask.bit_length() - 1 + ord("A")) if mask else ""
  • Python
  • answer
  • Hash table
  • One question daily
  • C++
  • Bit operation

show all >>

2315. Statistical star number One question daily

  2024-01-01
字数统计: 119字   |   阅读时长: 1min

2023-01-29.png
2315. Statistical star number

Thought:

mine:The simple version of the simple out of the stack into the stack
@ylq:right|Number count,The number is2Perform the multiple*Count

Code:

Out of the stack into the stack
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def countAsterisks(self, s: str) -> int:
stack = True
flag = 0
for i in s:
if stack:
if i == '*':
flag += 1
if i == '|' and stack:
stack = False
elif i == '|' and not stack:
stack = True
return flag
ylq
1
2
3
4
5
6
7
8
9
class Solution:
def countAsterisks(self, s: str) -> int:
count1, count2 = 0, 0
for i in range(len(s)):
if s[i] == '|':
count1 += 1
if count1 % 2 == 0 and s[i] == '*':
count2 += 1
return count2
  • Python
  • answer
  • One question daily

show all >>

2325Decrypt One question daily

  2024-01-01
字数统计: 160字   |   阅读时长: 1min

2023-02-01 (1).png
2325. Decrypt

Thought:

Simple hash mapping table,pythonUse ascii_lowercase[] Directly obtain a lowercase letter。
Golang Look at the answer of Lingshen,

“Imam on the space to the space,In this way, you don’t need to judge the space。”

Code:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from string import ascii_lowercase

class Solution:
def decodeMessage(self, key: str, message: str) -> str:
str1 = ''
dict1 = {}
index = 0
for i in key.replace(' ', ''):
if i not in dict1:
dict1[i] = ascii_lowercase[index]
index += 1
for i in message:
if i in dict1:
str1 += dict1[i]
else:
str1 += ' '
return str1
golang
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func decodeMessage(key string, message string) string {
mp := ['z' + 1]byte{' ': ' '}
cur := byte('a')
for _, c := range key {
if mp[c] == 0 {
mp[c] = cur
cur += 1
}
}
s := []byte(message)
for i, c := range s {
s[i] = mp[c]
}
return string(s)
}

  • Python
  • answer
  • Hash table
  • One question daily
  • golang

show all >>

2319Determine whether the matrix is ​​one X matrix One question daily

  2024-01-01
字数统计: 141字   |   阅读时长: 1min

topic:

2023-01-31 (2).png
2319. Determine whether the matrix is ​​one X matrix

Thought:

GolangPure violence,PythonLearn Spirit God
The downward bidding on the main diagonal needs to be satisfied:i=j
Opposition to the corner line is satisfied:i+j=n−1

Code:

1
2
3
4
5
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
return all(
(v != 0) == (i == j or i + j == len(grid) - 1) for i, row in enumerate(grid) for j, v in enumerate(row))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func checkXMatrix(grid [][]int) bool {
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[i]); j++ {
//Two numbers in the first line
if (i == j) || (i+j == len(grid)-1) {
if grid[i][j] == 0 {
return false
}
} else if grid[i][j] != 0 {
return false
}
}
}
return true
}
  • Python
  • answer

show all >>

2331Calculate the value of the Boolean binary tree One question daily

  2024-01-01
字数统计: 170字   |   阅读时长: 1min

topic:

2023-02-06.png
2331Calculate the value of the Boolean binary tree

Thought:

For the currentroot,in the case ofleaf root(That is, the left node is empty),Then judge the current Boolean value(The leaf node must be Boolean instead of judging)。
Otherwise,Until traversing the leaf node,After seeing the left and right children of a sub -tree,Judge the current Valtype,Finally seekingValValue。
ifValNot the root node,butValChildren’s nodes as other trees return to the previous layer。

Code:

1
2
3
4
5
6
7
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.left is None:
return bool(root.val)
l = self.evaluateTree(root.left)
r = self.evaluateTree(root.right)
return l or r if root.val == 2 else l and r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func evaluateTree(root *TreeNode) bool {
if root.Left == nil {
return root.Val == 1
}
l, r := evaluateTree(root.Left), evaluateTree(root.Right)
if root.Val == 2 {
return l || r
}
return l && r
}
  • Python
  • answer
  • Binary tree

show all >>

2335. The shortest total time to be filled with a cup One question daily

  2024-01-01
字数统计: 291字   |   阅读时长: 1min

topic:

2023-02-11.png
2335. The shortest total time to be filled with a cup.md

Thought:

  1. This question is very simple,但是我好像没用贪心的Thought。Look at the second test case and find it found,In fact, the minimum number of seconds is to avoid a certain number as much as possible0。
    So keep sorting,Always operate the two largest numbers。This sending can also be used for DoriamountCase,But because of sorting,I don’t know if it can be used for a large number。
    Look atylbBig,和我一样但是Big细节处理得很好,Two fewer judgments than me,Then it seems that the classification discussion method below may be a solution to the difficult situation。
  2. mathematical method?Sort the number of drinks from small to large,Set the quantity x,y,z。Our goal is to match the different drinks as much as possible。
    like$x+y<=z$,The answer isz。like反之,Then set$t=(x+y-z)$,t是偶数The answer is
    $ \frac{t−1}{2} +z$Plus one

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def fillCups(self, amount: List[int]) -> int:
amount.sort()
count = 0
# Try to avoid returning0
while amount[-1] > 0:
if amount[-1] > 0 and amount[1] > 0:
amount[-1] -= 1
amount[1] -= 1
count += 1
if amount[-1] > 0 and amount[1] == 0:
return count + amount[-1]
amount.sort()
return count
ylb-golang
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import "sort"

func fillCups(amount []int) int {
ans := 0
for amount[0] + amount[1] + amount[2] > 0 {
sort.Ints(amount)
ans ++
amount[2] --
if amount[1] > 0{
amount[1] --
}
}
return ans
}
  • Python
  • answer
  • One question daily
  • golang
  • dp

show all >>

2527.Query arrayXorBeautiful value Zhou Sai Third Question

  2024-01-01
字数统计: 267字   |   阅读时长: 1min

6289.Query array Xor Beautiful value。

This question has been studied for a long time,Discovering a mathematical problem,But I didn’t want to be transparent,Because unfamiliar or valuable。So there is no better solution。

The first is to read the question and learn(nums[i]|nums[j])&nums[k],becauseijkCan be any value in the array,So the tripleforcycle(It will definitely timeout),Then he was a little bit out of his own,Just a little bit,feeli,jThe value of the value is the same,So add an additional layer of judgment(Dictionary)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def xorBeauty(self, nums: List[int]) -> int:
ans = []
record = {}
for i in range(len(nums)):
for j in range(len(nums)):
for k in range(len(nums)):
if k not in record:
if (i,j) not in record.values():
record[k] = (i,j)
flag = (nums[i]|nums[j])&nums[k]
if flag not in ans:
ans.append(flag)
else:
ans.remove(flag)
if len(ans) == 0:
return 0
answer = ans[0]

for i in range(1,len(ans)):
answer ^= ans[i]
return answer

I have been thinking about how to judge the same situation when I go out today,As a result@Lingcha Mountain AifuSolution,One by one,That’s okay。

1
2
3
4
class Solution:
def xorBeauty(self, nums: List[int]) -> int:
return reduce(xor, nums)

Then do,Search online,It turns out that if the two values ​​are the same,for exampleA^B^A = B,Soappend,removeTo implement this function。at lastforcycle求异或值。

Big Big Code is still studyinging

  • Python
  • solved,answer

show all >>

24.Two or two exchanges linked watches

  2024-01-01
字数统计: 89字   |   阅读时长: 1min

topic:

Give you a linked list,Two or two exchanges are adjacent nodes,And return to the head node of the linked list after exchange。You must complete this question without modifying the internal value of the node(Right now,Can only exchange nodes)。

Exemplary example 1:

enter:head = [1,2,3,4]
Output:[2,1,4,3]

Exemplary example 2:

enter:head = []
Output:[]

Exemplary example 3:

enter:head = [1]
Output:[1]

hint:

  • The number of nodes in the linked list is in the range [0, 100] Inside
  • 0 <= Node.val <= 100
Related Topics
  • recursion
  • Linked

  • 👍 1785
  • 👎 0
  • 24.Two or two exchanges linked watches.md

    Thought:

    use head 表示原始Linked的头节点,新的Linked的第二个节点,use newHead 表示新的Linked的头节点,原始Linked的第二个节点,则原始Linked中的其余节点的头节点是 newHead.next。make head.next = swapPairs(newHead.next),Indicates two or two exchanges for the rest of the nodes,The new head node after the exchange is head The next node。然后make newHead.next = head,Right now完成了所有节点的交换。最后返回新的Linked的头节点 newHead。
    recursion.gif

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
    if not head or not head.next:
    return head
    virtual_head = head.next
    head.next = self.swapPairs(virtual_head.next)
    virtual_head.next = head
    return virtual_head
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Solution {
    public:
    ListNode* swapPairs(ListNode* head) {
    if (head == nullptr or head->next == nullptr){
    return head;
    }
    ListNode *yummyNode = head->next;
    head->next = swapPairs(yummyNode->next);
    yummyNode->next = head;
    return yummyNode;
    }
    };
    • Python
    • answer

    show all >>

    2639. Query the width of each column in the grid diagram

      2024-01-01
    字数统计: 205字   |   阅读时长: 1min

    topic:

    2639. Query the width of each column in the grid diagram.md

    Thought:

    The first thing I think is to usemapTo solve,[list(map(lambda x: len(str(x)), row)) for row in grid] Build such an expression,但是topic要求找到列的最大值,If it is done by yourself so manually, you need itO(n^2)Time complexity,SonumpyYou can easily find the iterative value of each column。

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import numpy as np

    class Solution:
    def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
    # let's convert the grid to a numpy array
    np_grid = np.array(grid, dtype=str)
    # calculate the length of each element in the grid
    lengths = np.vectorize(len)(np_grid)
    # find the maximum length of each column
    max_lengths = lengths.max(axis=0)
    return max_lengths.tolist()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    impl Solution {
    pub fn find_column_width(grid: Vec<Vec<i32>>) -> Vec<i32> {
    let col_n = grid[0].len();
    let mut ans = vec![0; col_n];

    for row in grid.iter() {
    for (i, &num) in row.iter().enumerate() {
    let length = num.to_string().len() as i32;
    if length > ans[i] {
    ans[i] = length;
    }
    }
    }
    ans
    }
    }
    • Python
    • answer

    show all >>

    << 上一页1…678910…15下一页 >>

    150 篇 | 131.7k
    次 | 人
    这里自动载入天数这里自动载入时分秒
    2022-2025 loong loong | 新南威尔士龙龙号