Skip to content

feat: add solutions to lc problems: No.0541,0542 #3317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 40 additions & 18 deletions solution/0500-0599/0541.Reverse String II/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ tags:

<!-- solution:start -->

### 方法一
### 方法一:双指针

我们可以遍历字符串 $\textit{s}$,每次遍历 $\textit{2k}$ 个字符,然后利用双指针技巧,对这 $\textit{2k}$ 个字符中的前 $\textit{k}$ 个字符进行反转。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $\textit{s}$ 的长度。

<!-- tabs:start -->

Expand All @@ -65,26 +69,27 @@ tags:
```python
class Solution:
def reverseStr(self, s: str, k: int) -> str:
t = list(s)
for i in range(0, len(t), k << 1):
t[i : i + k] = reversed(t[i : i + k])
return ''.join(t)
cs = list(s)
for i in range(0, len(cs), 2 * k):
cs[i : i + k] = reversed(cs[i : i + k])
return "".join(cs)
```

#### Java

```java
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i += (k << 1)) {
for (int st = i, ed = Math.min(chars.length - 1, i + k - 1); st < ed; ++st, --ed) {
char t = chars[st];
chars[st] = chars[ed];
chars[ed] = t;
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 0; i < n; i += k * 2) {
for (int l = i, r = Math.min(i + k - 1, n - 1); l < r; ++l, --r) {
char t = cs[l];
cs[l] = cs[r];
cs[r] = t;
}
}
return new String(chars);
return new String(cs);
}
}
```
Expand All @@ -95,7 +100,8 @@ class Solution {
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0, n = s.size(); i < n; i += (k << 1)) {
int n = s.size();
for (int i = 0; i < n; i += 2 * k) {
reverse(s.begin() + i, s.begin() + min(i + k, n));
}
return s;
Expand All @@ -107,13 +113,29 @@ public:

```go
func reverseStr(s string, k int) string {
t := []byte(s)
for i := 0; i < len(t); i += (k << 1) {
for st, ed := i, min(i+k-1, len(t)-1); st < ed; st, ed = st+1, ed-1 {
t[st], t[ed] = t[ed], t[st]
cs := []byte(s)
n := len(cs)
for i := 0; i < n; i += 2 * k {
for l, r := i, min(i+k-1, n-1); l < r; l, r = l+1, r-1 {
cs[l], cs[r] = cs[r], cs[l]
}
}
return string(t)
return string(cs)
}
```

#### TypeScript

```ts
function reverseStr(s: string, k: number): string {
const n = s.length;
const cs = s.split('');
for (let i = 0; i < n; i += 2 * k) {
for (let l = i, r = Math.min(i + k - 1, n - 1); l < r; l++, r--) {
[cs[l], cs[r]] = [cs[r], cs[l]];
}
}
return cs.join('');
}
```

Expand Down
58 changes: 40 additions & 18 deletions solution/0500-0599/0541.Reverse String II/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ tags:

<!-- solution:start -->

### Solution 1
### Solution 1: Two Pointers

We can traverse the string $\textit{s}$, iterating over every $\textit{2k}$ characters, and then use the two-pointer technique to reverse the first $\textit{k}$ characters among these $\textit{2k}$ characters.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $\textit{s}$.

<!-- tabs:start -->

Expand All @@ -53,26 +57,27 @@ tags:
```python
class Solution:
def reverseStr(self, s: str, k: int) -> str:
t = list(s)
for i in range(0, len(t), k << 1):
t[i : i + k] = reversed(t[i : i + k])
return ''.join(t)
cs = list(s)
for i in range(0, len(cs), 2 * k):
cs[i : i + k] = reversed(cs[i : i + k])
return "".join(cs)
```

#### Java

```java
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i += (k << 1)) {
for (int st = i, ed = Math.min(chars.length - 1, i + k - 1); st < ed; ++st, --ed) {
char t = chars[st];
chars[st] = chars[ed];
chars[ed] = t;
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 0; i < n; i += k * 2) {
for (int l = i, r = Math.min(i + k - 1, n - 1); l < r; ++l, --r) {
char t = cs[l];
cs[l] = cs[r];
cs[r] = t;
}
}
return new String(chars);
return new String(cs);
}
}
```
Expand All @@ -83,7 +88,8 @@ class Solution {
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0, n = s.size(); i < n; i += (k << 1)) {
int n = s.size();
for (int i = 0; i < n; i += 2 * k) {
reverse(s.begin() + i, s.begin() + min(i + k, n));
}
return s;
Expand All @@ -95,13 +101,29 @@ public:
```go
func reverseStr(s string, k int) string {
t := []byte(s)
for i := 0; i < len(t); i += (k << 1) {
for st, ed := i, min(i+k-1, len(t)-1); st < ed; st, ed = st+1, ed-1 {
t[st], t[ed] = t[ed], t[st]
cs := []byte(s)
n := len(cs)
for i := 0; i < n; i += 2 * k {
for l, r := i, min(i+k-1, n-1); l < r; l, r = l+1, r-1 {
cs[l], cs[r] = cs[r], cs[l]
}
}
return string(t)
return string(cs)
}
```

#### TypeScript

```ts
function reverseStr(s: string, k: number): string {
const n = s.length;
const cs = s.split('');
for (let i = 0; i < n; i += 2 * k) {
for (let l = i, r = Math.min(i + k - 1, n - 1); l < r; l++, r--) {
[cs[l], cs[r]] = [cs[r], cs[l]];
}
}
return cs.join('');
}
```

Expand Down
3 changes: 2 additions & 1 deletion solution/0500-0599/0541.Reverse String II/Solution.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0, n = s.size(); i < n; i += (k << 1)) {
int n = s.size();
for (int i = 0; i < n; i += 2 * k) {
reverse(s.begin() + i, s.begin() + min(i + k, n));
}
return s;
Expand Down
11 changes: 6 additions & 5 deletions solution/0500-0599/0541.Reverse String II/Solution.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
func reverseStr(s string, k int) string {
t := []byte(s)
for i := 0; i < len(t); i += (k << 1) {
for st, ed := i, min(i+k-1, len(t)-1); st < ed; st, ed = st+1, ed-1 {
t[st], t[ed] = t[ed], t[st]
cs := []byte(s)
n := len(cs)
for i := 0; i < n; i += 2 * k {
for l, r := i, min(i+k-1, n-1); l < r; l, r = l+1, r-1 {
cs[l], cs[r] = cs[r], cs[l]
}
}
return string(t)
return string(cs)
}
15 changes: 8 additions & 7 deletions solution/0500-0599/0541.Reverse String II/Solution.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i += (k << 1)) {
for (int st = i, ed = Math.min(chars.length - 1, i + k - 1); st < ed; ++st, --ed) {
char t = chars[st];
chars[st] = chars[ed];
chars[ed] = t;
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 0; i < n; i += k * 2) {
for (int l = i, r = Math.min(i + k - 1, n - 1); l < r; ++l, --r) {
char t = cs[l];
cs[l] = cs[r];
cs[r] = t;
}
}
return new String(chars);
return new String(cs);
}
}
8 changes: 4 additions & 4 deletions solution/0500-0599/0541.Reverse String II/Solution.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class Solution:
def reverseStr(self, s: str, k: int) -> str:
t = list(s)
for i in range(0, len(t), k << 1):
t[i : i + k] = reversed(t[i : i + k])
return ''.join(t)
cs = list(s)
for i in range(0, len(cs), 2 * k):
cs[i : i + k] = reversed(cs[i : i + k])
return "".join(cs)
10 changes: 10 additions & 0 deletions solution/0500-0599/0541.Reverse String II/Solution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function reverseStr(s: string, k: number): string {
const n = s.length;
const cs = s.split('');
for (let i = 0; i < n; i += 2 * k) {
for (let l = i, r = Math.min(i + k - 1, n - 1); l < r; l++, r--) {
[cs[l], cs[r]] = [cs[r], cs[l]];
}
}
return cs.join('');
}
70 changes: 32 additions & 38 deletions solution/0500-0599/0542.01 Matrix/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,17 @@ tags:

<!-- solution:start -->

### 方法一:多源 BFS
### 方法一:BFS

初始化结果矩阵 ans,所有 0 的距离为 0,所以 1 的距离为 -1。初始化队列 q 存储 BFS 需要检查的位置,并将所有 0 的位置入队
我们创建一个大小和 $\textit{mat}$ 一样的矩阵 $\textit{ans}$,并将所有的元素初始化为 $-1$

循环弹出队列 q 的元素 `p(i, j)`,检查邻居四个点。对于邻居 `(x, y)`,如果 `ans[x][y] = -1`,则更新 `ans[x][y] = ans[i][j] + 1`。同时将 `(x, y)` 入队。
然后我们遍历 $\textit{mat}$,将所有的 $0$ 元素的坐标 $(i, j)$ 加入队列 $\textit{q}$,并将 $\textit{ans}[i][j]$ 设为 $0$。

接下来,我们使用广度优先搜索,从队列中取出一个元素 $(i, j)$,并遍历其四个方向,如果该方向的元素 $(x, y)$ 满足 $0 \leq x < m$, $0 \leq y < n$ 且 $\textit{ans}[x][y] = -1$,则将 $\textit{ans}[x][y]$ 设为 $\textit{ans}[i][j] + 1$,并将 $(x, y)$ 加入队列 $\textit{q}$。

最后返回 $\textit{ans}$。

时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为矩阵 $\textit{mat}$ 的行数和列数。

<!-- tabs:start -->

Expand Down Expand Up @@ -219,8 +225,7 @@ function updateMatrix(mat: number[][]): number[][] {
}
}
const dirs: number[] = [-1, 0, 1, 0, -1];
while (q.length) {
const [i, j] = q.shift()!;
for (const [i, j] of q) {
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] === -1) {
Expand All @@ -239,49 +244,38 @@ function updateMatrix(mat: number[][]): number[][] {
use std::collections::VecDeque;

impl Solution {
#[allow(dead_code)]
pub fn update_matrix(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n: usize = mat.len();
let m: usize = mat[0].len();
let mut ret_vec: Vec<Vec<i32>> = vec![vec![-1; m]; n];
// The inner tuple is of <X, Y, Current Count>
let mut the_q: VecDeque<(usize, usize)> = VecDeque::new();
let traverse_vec: Vec<(i32, i32)> = vec![(-1, 0), (1, 0), (0, 1), (0, -1)];

// Initialize the queue
for i in 0..n {
for j in 0..m {
let m = mat.len();
let n = mat[0].len();
let mut ans = vec![vec![-1; n]; m];
let mut q = VecDeque::new();

for i in 0..m {
for j in 0..n {
if mat[i][j] == 0 {
// For the zero cell, enqueue at first
the_q.push_back((i, j));
// Set to 0 in return vector
ret_vec[i][j] = 0;
q.push_back((i, j));
ans[i][j] = 0;
}
}
}

while !the_q.is_empty() {
let (x, y) = the_q.front().unwrap().clone();
the_q.pop_front();
for pair in &traverse_vec {
let cur_x = pair.0 + (x as i32);
let cur_y = pair.1 + (y as i32);
if Solution::check_bounds(cur_x, cur_y, n as i32, m as i32)
&& ret_vec[cur_x as usize][cur_y as usize] == -1
{
// The current cell has not be updated yet, and is also in bound
ret_vec[cur_x as usize][cur_y as usize] = ret_vec[x][y] + 1;
the_q.push_back((cur_x as usize, cur_y as usize));
let dirs = [-1, 0, 1, 0, -1];
while let Some((i, j)) = q.pop_front() {
for k in 0..4 {
let x = i as isize + dirs[k];
let y = j as isize + dirs[k + 1];
if x >= 0 && x < m as isize && y >= 0 && y < n as isize {
let x = x as usize;
let y = y as usize;
if ans[x][y] == -1 {
ans[x][y] = ans[i][j] + 1;
q.push_back((x, y));
}
}
}
}

ret_vec
}

#[allow(dead_code)]
pub fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool {
i >= 0 && i < n && j >= 0 && j < m
ans
}
}
```
Expand Down
Loading
Loading