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

9021_TUT_1

  2024-09-11
字数统计: 626字   |   阅读时长: 3min

Slide 1: Introduction

Today, we are going to walk through six Python functions that perform various tasks involving integers, lists, and text files. Each function demonstrates different ways to manipulate data, including string formatting, list processing, and reading from files.

Slide 2: Function 1 - f1(m, n)

The first function, f1, generates a simple string pattern. Here’s how it works:

1
2
def f1(m, n):
return ('|' + '_' * n + '|') * m
  1. The function takes two integer arguments, m and n. Both are assumed to be at least 0.
  2. It constructs a pattern consisting of vertical bars (|) enclosing underscores (_), repeated m times. The number of underscores between the bars is determined by n.
  3. For example, if m = 3 and n = 4, the output would be:
1
|____||____||____|

Slide 3: Function 2 - f2(n)

The second function, f2, creates a square pattern made up of digits. Here’s the function:

1
2
def f2(n):
return (str(n) * n + '\n') * n
  1. This function takes an integer n and generates a square of n rows, where each row contains the digit n repeated n times.
  2. The pattern ends with a newline after each row.
  3. For example, if n = 3, the output will be:
1
2
3
333
333
333

Slide 4: Function 3 - f3(L)

Next, we have f3, which works on a list of integers:

1
2
3
4
def f3(L):
while len(L) > 1 and L[0] > L[1]:
L.remove(L[0])
print(L)
  1. This function removes elements from the start of the list until the first two consecutive elements are in non-decreasing order.
  2. The process continues as long as the first element is strictly greater than the second element.
  3. Once the list is stable, it prints the modified list.
  4. For example, if L = [9, 8, 7, 10], the function will remove 9, 8, and 7, leaving [10].

Slide 5: Function 4 - f4(D, n)

The fourth function, f4, works with dictionaries:

1
2
3
4
5
6
7
8
def f4(D, n):
if n not in D:
return []
ans = [n]
while n in D and D[n] > n:
ans.append(D[n])
n = D[n]
return ans
  1. This function takes a dictionary D and an integer n. It generates a strictly increasing sequence of integers based on the relationships defined in the dictionary.
  2. Starting from n, it appends D[n], D[D[n]], and so on to the list, as long as each subsequent value is greater than the previous one.
  3. For example, if D = {1: 2, 2: 3, 3: 5} and n = 1, the function will return [1, 2, 3, 5].

Slide 6: Function 5 - f5(filename)

The fifth function, f5, reads from a file and processes each line:

1
2
3
4
5
6
def f5(filename):
with open(filename) as f:
for i in f:
name, number = i.split(',')
number = int(number) * 1000
print(f"{number} people named {name}")
  1. This function reads a text file, where each line consists of a name and a count separated by a comma.
  2. The function multiplies the count by 1000 and prints the result in the format: “X people named Y”.
  3. For example, if the file contains a line “John,5”, it will print:
1
5000 people named John

Slide 7: Function 6 - f6(filename)

The final function, f6, also reads from a text file, but with a different format:

1
2
3
4
5
6
def f6(filename):
with open(filename) as f:
for i in f:
if not i.isspace():
number, charactor = i.split()
print(int(number) * charactor)
  1. This function reads lines that contain an integer followed by a symbol (e.g., “5 *”).
  2. It multiplies the symbol by the integer and prints the result.
  3. For example, if the file contains the line “3 # “, the function will print:
1
### 
  • Python
  • Tutorial

show all >>

Top of an article

  2024-08-07
字数统计: 322字   |   阅读时长: 1min

longsizhuo123.github.io

pattern_stripes-1_1_2_0-0_125_1__cc2a35_4f372d_00a1b0_edc951_eb6941

“Maybe it could be a nice memory”

Welcome to my personal blog repository on Github! My name is Sizhuo Long, and I am currently a student in Australia. This repository is home to my personal blog, which is built using the HEXO static site generator.

On my blog, you’ll find a variety of content including my thoughts on technology, programming, and the latest developments in my field of study. I also share my experiences and lessons learned from the projects I’ve worked on.

I hope that by sharing my knowledge and insights, I can help others who are interested in the same topics. I welcome any comments and feedback, and I am always open to collaboration.

Thank you for visiting my blog, I hope you will find something interesting here. And I would really appreciate it if you could pay more attention to my blog and follow me.

Why you should follow me

  • I’ll share my personal experiences and thoughts on technology and programming
  • I’ll keep you updated on the latest developments in my field of study
  • I’m open to collaboration and feedback.

How to contact me

  • Email: longsizhuo@gmail.com
  • LinkedIn: Sizhuo Long
  • XiaoHongShu(Small RedBook): @sizhuo_long

Thank you for reading, and I hope you enjoy my blog!

pattern_stripes-1_1_2_0-0_125_1__cc2a35_4f372d_00a1b0_edc951_eb6941

Single -cellRNAData analysis tool
The project I did before,There are many errors,Don’t spray。
Shu Di Travel Bacteria
This is a small assignment when I was a second junior year,It’s a group operation。At first I couldn’t get the linkhtmldocument,I read a lot of official documents orCSDNdocument
。Finally read an article,Said to beHEXODang thegeneratewhen,I willsource中的documentappendarrivepublicMiddle,I tried many times later,Discover directly
public为源document夹,Just call the directory。Although this will cause it to be unable to bemddocument中超链接arrivedocument。

at the same time,也exist新的bugunsolved:login.htmlUnable toindex.htmlJump
Linkin:

Sizhuo Long
置顶
  • unsolved
  • front end

show all >>

964E

  2024-08-07
字数统计: 527字   |   阅读时长: 3min

Question:

E. Triple Operations
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

On the board Ivy wrote down all integers from ll to rr, inclusive.

In an operation, she does the following:

  • pick two numbers xx and yy on the board, erase them, and in their place write the numbers 3x3x and ⌊y3⌋⌊y3⌋. (Here ⌊∙⌋⌊∙⌋ denotes rounding down to the nearest integer).

What is the minimum number of operations Ivy needs to make all numbers on the board equal 00? We have a proof that this is always possible.

Input

The first line contains an integer tt (1≤t≤1041≤t≤104) — the number of test cases.

The only line of each test case contains two integers ll and rr (1≤l<r≤2⋅1051≤l<r≤2⋅105).

Output

For each test case, output a single integer — the minimum number of operations needed to make all numbers on the board equal 00.

Example
Input
Copy
4
1 3
2 4
199999 200000
19 84
Output
Copy
5
6
36
263
Note

In the first test case, we can perform 55 operations as follows:

1,2,3−→−−−−x=1,y=23,0,3−→−−−−x=0,y=31,0,3−→−−−−x=0,y=31,0,1−→−−−−x=0,y=10,0,1−→−−−−x=0,y=10,0,0.1,2,3→x=1,y=23,0,3→x=0,y=31,0,3→x=0,y=31,0,1→x=0,y=10,0,1→x=0,y=10,0,0.

[964E.md](https://codeforces.com/contest/1999/problem/E)

My think:

At first, I thought it was a simple simulation problem: calculate the number of times x when the smallest
number divided by 3 equals 0, and then the answer would be x * 2 plus the number of remaining times when
the left number divided by 3 equals 0. However, this approach is incorrect.

By utilizing the characteristics of exponential growth and performing some simple
calculations, we can quickly determine the minimum number of operations within a given range.
This method has a low time complexity and can efficiently handle large input ranges.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import math
t = int(input())
for i in range(t):
num = list(map(int, input().split()))
l = num[0]
r = num[1]
start_pow3 = 1
cnt_start = 1
while start_pow3 <= (l / 3):
start_pow3 *= 3
cnt_start += 1
ans = cnt_start
pow3 = start_pow3
next_pow3 = start_pow3 * 3
while pow3 <= r:
ans += (min(r + 1, next_pow3) - max(l, pow3)) * cnt_start
cnt_start += 1
pow3 *= 3
next_pow3 *= 3
print(ans)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def min_operations_to_zero(n):
operations = 0
while n > 0:
n = n // 3
operations += 1
return operations

t = int(input())
results = []
for _ in range(t):
l, r = map(int, input().split())
total_operations = 0
oper = min_operations_to_zero(l)
for n in range(l+1, r+1):
total_operations += min_operations_to_zero(n)
total_operations += oper*2
results.append(total_operations)

for result in results:
print(result)
  • Python
  • Answer

show all >>

994.Rotten orange

  2024-05-14
字数统计: 739字   |   阅读时长: 4min

topic:

“””

Given m x n grid  grid middle,Each cell can have one of the following three values:

  • value 0 Represents the empty unit;
  • value 1 Represents fresh oranges;
  • value 2 代表Rotten orange。

every minute,Rotten orange around 4 Adjacent in this direction Fresh oranges will rot。

return 直到单元格middle没有新鲜橘子为止所必须经过的最小分钟数。If it is impossible,return -1 。

 

Exemplary example 1:

enter:grid = [[2,1,1],[1,1,0],[0,1,1]]
Output:4

Exemplary example 2:

enter:grid = [[2,1,1],[0,1,1],[1,0,1]]
Output:-1
explain:Orange in the lower left corner(First 2 OK, First 0 List)Never rot,Because rotten will only happen in 4 In the direction。

Exemplary example 3:

enter:grid = [[0,2]]
Output:0
explain:because 0 There is no fresh orange in minutes,So the answer is 0 。

 

hint:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] Only for 0、1 or 2
Related Topics
  • Priority search
  • Array
  • matrix

  • 👍 872
  • 👎 0
  • """

    Thought:

    这个问题可以用Priority search(BFS)To solve。We need to track the spread of rotten oranges,Record time,And check if there is a fresh orange that cannot be rotten。The initial idea of ​​the original idea:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
    bad_orange = []
    # 找到所有初始Rotten orange
    for i in range(len(grid)):
    for j in range(len(grid[0])):
    if grid[i][j] == 2:
    # 存入初始队List
    bad_orange.append((i, j))

    Similar to multi -threaded,每个线程存入一个初始队List,初始队List通过BFSGradual diffusion

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    from collections import deque

    class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
    bad_orange = deque()
    fresh_oranges = 0
    rows, cols = len(grid), len(grid[0])

    # 找到所有初始Rotten orange,And calculate the number of fresh oranges
    for i in range(rows):
    for j in range(cols):
    if grid[i][j] == 2:
    bad_orange.append((i, j))
    elif grid[i][j] == 1:
    fresh_oranges += 1

    # 方向Array:up down left right
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

    # If there is no fresh orange,直接return 0
    if fresh_oranges == 0:
    return 0

    # BFS
    minutes = 0
    while bad_orange:
    minutes += 1
    for _ in range(len(bad_orange)):
    x, y = bad_orange.popleft()
    for dx, dy in directions:
    nx, ny = x + dx, y + dy
    if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1:
    grid[nx][ny] = 2
    fresh_oranges -= 1
    bad_orange.append((nx, ny))

    # If there are fresh oranges,return -1
    return minutes - 1 if fresh_oranges == 0 else -1
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    import (
    "sync"
    )

    func orangesRotting(grid [][]int) int {
    rows, cols := len(grid), len(grid[0])
    badOranges := make([][2]int, 0)
    freshOranges := 0

    // 找到所有初始Rotten orange,And calculate the number of fresh oranges
    for r := 0; r < rows; r++ {
    for c := 0; c < cols; c++ {
    if grid[r][c] == 2 {
    badOranges = append(badOranges, [2]int{r, c})
    } else if grid[r][c] == 1 {
    freshOranges += 1
    }
    }
    }

    // If there is no fresh orange,直接return 0
    if freshOranges == 0 {
    return 0
    }

    directions := [][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
    minutes := 0

    var wg sync.WaitGroup

    // BFS
    for len(badOranges) > 0 {
    minutes++
    nextBadOranges := make([][2]int, 0)
    for _, orange := range badOranges {
    x, y := orange[0], orange[1]
    wg.Add(1)
    go func(x, y int) {
    defer wg.Done()
    for _, d := range directions {
    nx, ny := x+d[0], y+d[1]
    if nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == 1 {
    grid[nx][ny] = 2
    nextBadOranges = append(nextBadOranges, [2]int{nx, ny})
    freshOranges--
    }
    }
    }(x, y)
    }
    wg.Wait()
    badOranges = nextBadOranges
    }

    // If there are fresh oranges,return -1
    if freshOranges > 0 {
    return -1
    }
    return minutes - 1
    }
    • Python
    • BFS
    • Bilateral queue

    show all >>

    1017. Negative binary conversion

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

    topic:

    1017. Negative binary conversion

    Thought:

    The difference from binary is just not always//2,It’s every number//-1

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Solution:
    def baseNeg2(self, n: int) -> str:
    k = 1
    ans = []
    while n:
    if n % 2:
    ans.append('1')
    n -= k
    else:
    ans.append('0')
    n //= 2
    k *= -1
    return ''.join(ans[::-1]) or '0'
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    impl Solution {
    pub fn base_neg2(mut n: i32) -> String {
    let mut ans = Vec::new();
    while n != 0 {
    if n % 2 != 0 {
    ans.push('1');
    n = (n - 1) / -2;
    } else {
    ans.push('0');
    n /= -2;
    }
    }
    if ans.is_empty() {
    ans.push('0');
    }
    ans.reverse();
    ans.iter().collect()
    }
    }
    • Python
    • answer

    show all >>

    1017.Negative binary conversion

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

    topic:

    Give you an integer n ,Return to the integer in the form of a binary string Negative binary(base -2)express。

    Notice,Unless the string is "0",Otherwise, the returned string cannot contain the front guide zero。

     

    Exemplary example 1:

    enter:n = 2
    Output:"110"
    explain:(-2)2 + (-2)1 = 2
    

    Exemplary example 2:

    enter:n = 3
    Output:"111"
    explain:(-2)2 + (-2)1 + (-2)0 = 3
    

    Exemplary example 3:

    enter:n = 4
    Output:"100"
    explain:(-2)2 = 4
    

     

    hint:

    • 0 <= n <= 109
    Related Topics
  • math

  • 👍 111
  • 👎 0
  • [1017.Negative binary conversion.md]()

    Thought:

    We can judge n Every bit from low to high,If the bit is 1,Then the answer is 1,Otherwise 0。If the bit is 1,So we need to n minus k。Next we update n=⌊n/2⌋, k=−k。Continue to judge the next。
    at last,We will return to the answer。
    time complexity O(logn),in n For the given integer。Ignore the space consumption of the answer,Spatial complexity O(1)。

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Solution:
    def baseNeg2(self, n: int) -> str:
    k = 1
    ans = []
    while n:
    if n % 2:
    ans.append('1')
    n -= k
    else:
    ans.append('0')
    n //= 2
    k *= -1
    return ''.join(ans[::-1]) or '0'
    • Python
    • answer

    show all >>

    1124. The longest period of performance One question daily

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

    topic:

    2023-02-15.png
    1124. The longest period of performance.md

    Thought:

    This question is not,I thought it was a double pointer but timeout over time,结果是Prefix and算法。The following isSpiritual godSolution
    通过Prefix and,我们可以把Elements and elements of sub -array转换成两个Prefix and的差,Right now
    $$
    \sum_{j=left}^{right} nums[j] = \sum_{j=0}^{right} nums[j]− \sum_{j=0}^{left-1} nums[j]=s[right+1]−s[left]
    $$
    Now that I said it「Elements and elements of sub -array」,那么利用Prefix and s,Turn the problem to:
    Find two bidding i and j,satisfy j<ij<ij<i and s[j]<s[i],maximize i−jValue。

    Code:

    Double pointer
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Solution:
    def longestWPI(self, hours: List[int]) -> int:
    ans = 0
    for index, i in enumerate(hours):
    count = 0
    j = index
    while j < len(hours):
    if hours[j] <= 8:
    count -= 1
    elif hours[j] > 8:
    count += 1
    if count > 0:
    ans = max(ans, j - index + 1)
    j += 1
    return ans
    Prefix and
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Solution:
    def longestWPI(self, hours: List[int]) -> int:
    n = len(hours)
    s = [0] * (n + 1)
    st = [0]
    for j, h in enumerate(hours, 1):
    s[j] = s[j - 1] + (1 if h > 8 else -1)
    if s[j] < s[st[-1]]:
    st.append(j)
    ans = 0
    for i in range(n, 0 , -1):
    while st and s[i] > s[st[-1]]:
    ans = max(ans, i-st.pop())
    return ans
    • Python
    • answer
    • Prefix and

    show all >>

    1138. The path on the letter board One question daily

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

    topic:

    2023-02-12.png
    1138. The path on the letter board One question daily.md

    Thought:

    Read the wrong questions,According to the method of random letters above the subtitle version。butzSpecial circumstances are not considered,I thought about it later,Just turn the column into a line,Time complexity isOn3
    。Look atylbs answer,Use directlyasciiThe code watch simulates a letter board。

    From the starting point (0,0)(0, 0)(0,0) Set off,Simulate each step of movement,Style the movement of each step into the answer。Pay attention to the direction of moving“Left、superior、right、Down”Order。

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    class Solution:
    def alphabetBoardPath(self, target: str) -> str:
    str1 = ""
    board = ["abcde",
    "fghij",
    "klmno",
    "pqrst",
    "uvwxy",
    "z"]
    now_i = 0
    now_j = 0
    for i in board:
    for j,value in enumerate(i):
    pass
    for char in target:
    # See which line is
    for i in range(len(board)):
    if char in board[i]:
    if i - now_i > 0:
    str1 += 'D' * (i - now_i)
    if i - now_i < 0:
    str1 += 'U' * (now_i - i)
    now_i = i
    # Which column
    for j, value in enumerate(board[i]):
    if value == char:
    if j - now_j > 0:
    str1 += 'R' * (j - now_j)
    if j - now_j < 0:
    str1 += 'L' * (now_j - j)
    str1 += '!'
    now_j = j
    return str1
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class Solution:
    def alphabetBoardPath(self, target: str) -> str:
    i = j = 0
    ans = []
    for char in target:
    v = ord(char) - ord("a")
    x, y = v // 5, v % 5
    while j > y:
    j -= 1
    ans.append("L")
    while i > x:
    i -= 1
    ans.append("U")
    while j < y:
    j += 1
    ans.append("R")
    while i < x:
    i += 1
    ans.append("D")
    ans.append("!")
    return "".join(ans)
    • Python
    • answer

    show all >>

    1139. The greatest 1 Formation of the border One question daily

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

    topic:

    2023-02-17.png
    1139. The greatest 1 Formation of the border.md

    Thought:

    quiz6 Simple version,Prefix and求解。It should be noted that the upper left corner is0 Special circumstances are not considered,
    Need to verify # superior Left Down right Four -edge 1 The number of individuals d

    Code:

    错误Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    class Solution:
    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
    matrix_heng = copy.deepcopy(grid)
    matrix_su = copy.deepcopy(grid)
    ans = 0
    if len(grid) == 1:
    if 1 in grid[0]:
    return 1
    else:return 0
    for ind, i in enumerate(grid):
    for index in range(len(i)):
    # Each line adds
    if index >= 1:
    matrix_heng[ind][index] += matrix_heng[ind][index-1]
    # Add each column
    if ind >= 1:
    matrix_su[ind][index] += matrix_su[ind-1][index]
    print(matrix_heng, matrix_su)
    for i in range(len(grid)):
    for j in range(len(grid[i])):
    minus = min(matrix_heng[i][j], matrix_su[i][j])
    try:
    if grid[i-minus+1][j-minus+1] == 1 and i >= minus-1 and j >= minus-1:
    ans = max(ans, minus ** 2)
    except:
    pass
    return ans
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Solution:
    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
    m, n = len(grid), len(grid[0])
    rs = [list(accumulate(row, initial=0)) for row in grid] # 每行的Prefix and
    cs = [list(accumulate(col, initial=0)) for col in zip(*grid)] # 每列的Prefix and
    for d in range(min(m, n), 0, -1): # From large to small enumeration square edges d
    for i in range(m - d + 1):
    for j in range(n - d + 1): # 枚举正方形Leftsuperior角坐标 (i,j)
    # superior Left Down right Four -edge 1 The number of individuals d
    if rs[i][j + d] - rs[i][j] == d and \
    cs[j][i + d] - cs[j][i] == d and \
    rs[i + d - 1][j + d] - rs[i + d - 1][j] == d and \
    cs[j + d - 1][i + d] - cs[j + d - 1][i] == d:
    return d * d
    return 0
    • Python
    • answer
    • Prefix and

    show all >>

    1234. Replace the sub -string to get a balanced string One question daily

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

    topic:

    2023-02-13.png
    1234. Replace the sub -string to get a balanced string.md

    Thought:

    all():if bool(x) For all the values ​​in iterative objects x All for True,Then return True。 if可迭代对象为空,Then return True。

    Tongxiang dual pointer,The solution of the spiritual god of this question。
    If in this string,These four characters happen just to appear n/4 Second-rate,Then it is one「Balanced string」。
    if在待替换子串之外的任意字符的出现Second-rate数都Exceed $m=\dfrac{n}{4}$
    ,So no matter how you replace it,都无法make这个字符的出现Second-rate数等于m。
    on the other hand,if在待替换子串之外的任意字符的出现Second-rate数都不Exceed m,

    So it can be replaced ,make s 为Balanced string,即每个字符的出现Second-rate数均为 m。
    For this question,The left and right end points of the sub -string are left and right,enumerate right,
    if子串外的任意字符的出现Second-rate数都不Exceedm,The explanation from left arrive
    rightThis sub -string can be to replace the sub -string,Length right−left+1
    Update the minimum value of the answer,Move to the right left,Sumid sub -string length。

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Solution:
    def balancedString(self, s: str) -> int:
    s_c = Counter(s)
    n = len(s)
    if all(s_c[v] <= n//4 for v in s_c):
    return 0
    ans, left = inf, 0
    # enumerate右端点
    for i, j in enumerate(s):
    s_c[j] -= 1
    while all(s_c[v] <= n // 4 for v in s_c):
    ans = min(ans, i - left + 1)
    s_c[s[left]] += 1
    left += 1
    return ans

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    func balancedString(s string) int {
    cnt, m := ['X']int{}, len(s)/4
    for _, c := range s {
    cnt[c]++
    }
    if cnt['Q'] == m && cnt['W'] == m && cnt['E'] == m && cnt['R'] == m {
    return 0
    }
    ans, left := len(s), 0
    for right, c := range s {
    cnt[c]--
    for cnt['Q'] <= m && cnt['W'] <= m && cnt['E'] <= m && cnt['R'] <= m {
    ans = min(ans, right-left+1)
    cnt[s[left]]++
    left++
    }
    }
    return ans
    }
    func min(a, b int) int { if a > b { return b }; return a }
    • Python
    • answer

    show all >>

    << 上一页123456…15下一页 >>

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