Skip to content

Commit

Permalink
feat: update solutions to lc problems: No.2108,2109
Browse files Browse the repository at this point in the history
* No.2108.Find First Palindromic String in the Array
* No.2109.Adding Spaces to a String
  • Loading branch information
yanglbme committed Jun 22, 2024
1 parent 7c1baa8 commit 7bef4b7
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 201 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ tags:

### 方法一:模拟

遍历数组 `words`,对于每个字符串 `w`,判断其是否为回文字符串,如果是,则返回 `w`,否则继续遍历。
我们遍历数组 `words`,对于每个字符串 `w`,判断其是否为回文字符串,如果是,则返回 `w`,否则继续遍历。

判断一个字符串是否为回文字符串,可以使用双指针,分别指向字符串的首尾,向中间移动,判断对应的字符是否相等。如果遍历完整个字符串,都没有发现不相等的字符,则该字符串为回文字符串。

时间复杂度 $O(L)$,空间复杂度 $O(1)$,其中 $L$ 为数组 `words` 中所有字符串的长度之和。
时间复杂度 $O(L)$,其中 $L$ 为数组 `words` 中所有字符串的长度之和。空间复杂度 $O(1)$

<!-- tabs:start -->

Expand Down Expand Up @@ -148,21 +148,7 @@ func firstPalindrome(words []string) string {

```ts
function firstPalindrome(words: string[]): string {
for (const word of words) {
let left = 0;
let right = word.length - 1;
while (left < right) {
if (word[left] !== word[right]) {
break;
}
left++;
right--;
}
if (left >= right) {
return word;
}
}
return '';
return words.find(w => w === w.split('').reverse().join('')) || '';
}
```

Expand All @@ -171,19 +157,9 @@ function firstPalindrome(words: string[]): string {
```rust
impl Solution {
pub fn first_palindrome(words: Vec<String>) -> String {
for word in words.iter() {
let s = word.as_bytes();
let mut left = 0;
let mut right = s.len() - 1;
while left < right {
if s[left] != s[right] {
break;
}
left += 1;
right -= 1;
}
if left >= right {
return word.clone();
for w in words {
if w == w.chars().rev().collect::<String>() {
return w;
}
}
String::new()
Expand All @@ -195,18 +171,17 @@ impl Solution {

```c
char* firstPalindrome(char** words, int wordsSize) {
for (int i = 0; i < wordsSize; i++) {
int left = 0;
int right = strlen(words[i]) - 1;
while (left < right) {
if (words[i][left] != words[i][right]) {
break;
for (int i = 0; i < wordsSize; ++i) {
char* w = words[i];
int len = strlen(w);
bool ok = true;
for (int j = 0, k = len - 1; j < k && ok; ++j, --k) {
if (w[j] != w[k]) {
ok = false;
}
left++;
right--;
}
if (left >= right) {
return words[i];
if (ok) {
return w;
}
}
return "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,13 @@ Note that &quot;racecar&quot; is also palindromic, but it is not the first.

<!-- solution:start -->

### Solution 1
### Solution 1: Simulation

We iterate through the array `words`, for each string `w`, we determine if it is a palindrome. If it is, then we return `w`; otherwise, we continue to iterate.

To determine if a string is a palindrome, we can use two pointers, one pointing to the start and the other to the end of the string, moving towards the center, and checking if the corresponding characters are equal. If, after traversing the entire string, no unequal characters are found, then the string is a palindrome.

The time complexity is $O(L)$, where $L$ is the sum of the lengths of all strings in the array `words`. The space complexity is $O(1)$.

<!-- tabs:start -->

Expand Down Expand Up @@ -143,21 +149,7 @@ func firstPalindrome(words []string) string {

```ts
function firstPalindrome(words: string[]): string {
for (const word of words) {
let left = 0;
let right = word.length - 1;
while (left < right) {
if (word[left] !== word[right]) {
break;
}
left++;
right--;
}
if (left >= right) {
return word;
}
}
return '';
return words.find(w => w === w.split('').reverse().join('')) || '';
}
```

Expand All @@ -166,19 +158,9 @@ function firstPalindrome(words: string[]): string {
```rust
impl Solution {
pub fn first_palindrome(words: Vec<String>) -> String {
for word in words.iter() {
let s = word.as_bytes();
let mut left = 0;
let mut right = s.len() - 1;
while left < right {
if s[left] != s[right] {
break;
}
left += 1;
right -= 1;
}
if left >= right {
return word.clone();
for w in words {
if w == w.chars().rev().collect::<String>() {
return w;
}
}
String::new()
Expand All @@ -190,18 +172,17 @@ impl Solution {

```c
char* firstPalindrome(char** words, int wordsSize) {
for (int i = 0; i < wordsSize; i++) {
int left = 0;
int right = strlen(words[i]) - 1;
while (left < right) {
if (words[i][left] != words[i][right]) {
break;
for (int i = 0; i < wordsSize; ++i) {
char* w = words[i];
int len = strlen(w);
bool ok = true;
for (int j = 0, k = len - 1; j < k && ok; ++j, --k) {
if (w[j] != w[k]) {
ok = false;
}
left++;
right--;
}
if (left >= right) {
return words[i];
if (ok) {
return w;
}
}
return "";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
char* firstPalindrome(char** words, int wordsSize) {
for (int i = 0; i < wordsSize; i++) {
int left = 0;
int right = strlen(words[i]) - 1;
while (left < right) {
if (words[i][left] != words[i][right]) {
break;
for (int i = 0; i < wordsSize; ++i) {
char* w = words[i];
int len = strlen(w);
bool ok = true;
for (int j = 0, k = len - 1; j < k && ok; ++j, --k) {
if (w[j] != w[k]) {
ok = false;
}
left++;
right--;
}
if (left >= right) {
return words[i];
if (ok) {
return w;
}
}
return "";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
impl Solution {
pub fn first_palindrome(words: Vec<String>) -> String {
for word in words.iter() {
let s = word.as_bytes();
let mut left = 0;
let mut right = s.len() - 1;
while left < right {
if s[left] != s[right] {
break;
}
left += 1;
right -= 1;
}
if left >= right {
return word.clone();
for w in words {
if w == w.chars().rev().collect::<String>() {
return w;
}
}
String::new()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,3 @@
function firstPalindrome(words: string[]): string {
for (const word of words) {
let left = 0;
let right = word.length - 1;
while (left < right) {
if (word[left] !== word[right]) {
break;
}
left++;
right--;
}
if (left >= right) {
return word;
}
}
return '';
return words.find(w => w === w.split('').reverse().join('')) || '';
}
42 changes: 8 additions & 34 deletions solution/2100-2199/2109.Adding Spaces to a String/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ tags:

### 方法一:双指针

我们可以用双指针 $i$ 和 $j$ 分别指向字符串 $s$ 和数组 $spaces$ 的头部,然后从头到尾遍历字符串 $s$,当 $i$ 等于 $spaces[j]$ 时,我们往结果字符串中添加一个空格,然后 $j$ 自增 1。接下来,我们将 $s[i]$ 添加到结果字符串中,然后 $i$ 自增 1。继续这个过程,直到遍历完字符串 $s$。
我们可以用双指针 $i$ 和 $j$ 分别指向字符串 $s$ 和数组 $\text{spaces}$ 的头部,然后从头到尾遍历字符串 $s$,当 $i$ 等于 $\text{spaces}[j]$ 时,我们往结果字符串中添加一个空格,然后 $j$ 自增 $1$。接下来,我们将 $s[i]$ 添加到结果字符串中,然后 $i$ 自增 $1$。继续这个过程,直到遍历完字符串 $s$。

时间复杂度 $O(n + m)$,其中 $n$ 和 $m$ 分别是字符串 $s$ 和数组 $spaces$ 的长度。忽略答案的空间消耗,空间复杂度 $O(1)$
时间复杂度 $O(n + m)$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是字符串 $s$ 和数组 $spaces$ 的长度。

<!-- tabs:start -->

Expand Down Expand Up @@ -160,46 +160,20 @@ func addSpaces(s string, spaces []int) string {

```ts
function addSpaces(s: string, spaces: number[]): string {
let ans = '';
const ans: string[] = [];
for (let i = 0, j = 0; i < s.length; i++) {
if (j < spaces.length && i === spaces[j]) {
ans += ' ';
++j;
if (i === spaces[j]) {
ans.push(' ');
j++;
}
ans += s[i];
ans.push(s[i]);
}
return ans;
return ans.join('');
}
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- solution:start -->

### 方法二

<!-- tabs:start -->

#### Python3

```python
class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
ans = []
i, j = len(s) - 1, len(spaces) - 1
while i >= 0:
ans.append(s[i])
if j >= 0 and i == spaces[j]:
ans.append(' ')
j -= 1
i -= 1
return ''.join(ans[::-1])
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- problem:end -->
44 changes: 11 additions & 33 deletions solution/2100-2199/2109.Adding Spaces to a String/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ We are also able to place spaces before the first character of the string.

<!-- solution:start -->

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

We can use two pointers $i$ and $j$ to point to the beginning of the string $s$ and the array $\text{spaces}$, respectively. Then, we iterate through the string $s$ from the beginning to the end. When $i$ equals $\text{spaces}[j]$, we add a space to the result string, and then increment $j$ by $1$. Next, we add $s[i]$ to the result string, and then increment $i$ by $1$. We continue this process until we have iterated through the entire string $s$.

The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the string $s$ and the array $spaces$, respectively.

<!-- tabs:start -->

Expand Down Expand Up @@ -152,46 +156,20 @@ func addSpaces(s string, spaces []int) string {

```ts
function addSpaces(s: string, spaces: number[]): string {
let ans = '';
const ans: string[] = [];
for (let i = 0, j = 0; i < s.length; i++) {
if (j < spaces.length && i === spaces[j]) {
ans += ' ';
++j;
if (i === spaces[j]) {
ans.push(' ');
j++;
}
ans += s[i];
ans.push(s[i]);
}
return ans;
return ans.join('');
}
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- solution:start -->

### Solution 2

<!-- tabs:start -->

#### Python3

```python
class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
ans = []
i, j = len(s) - 1, len(spaces) - 1
while i >= 0:
ans.append(s[i])
if j >= 0 and i == spaces[j]:
ans.append(' ')
j -= 1
i -= 1
return ''.join(ans[::-1])
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- problem:end -->
12 changes: 6 additions & 6 deletions solution/2100-2199/2109.Adding Spaces to a String/Solution.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
function addSpaces(s: string, spaces: number[]): string {
let ans = '';
const ans: string[] = [];
for (let i = 0, j = 0; i < s.length; i++) {
if (j < spaces.length && i === spaces[j]) {
ans += ' ';
++j;
if (i === spaces[j]) {
ans.push(' ');
j++;
}
ans += s[i];
ans.push(s[i]);
}
return ans;
return ans.join('');
}
Loading

0 comments on commit 7bef4b7

Please sign in to comment.