Skip to content

Commit d950d45

Browse files
committed
Merge branch 'master' of github.com:BaffinLee/leetcode-javascript
2 parents 78699c7 + 0d8f2a8 commit d950d45

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# 1750. Minimum Length of String After Deleting Similar Ends
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Two Pointers, String.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times:
10+
11+
12+
13+
- Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal.
14+
15+
- Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal.
16+
17+
- The prefix and the suffix should not intersect at any index.
18+
19+
- The characters from the prefix and suffix must be the same.
20+
21+
- Delete both the prefix and the suffix.
22+
23+
24+
Return **the **minimum length** of **`s` **after performing the above operation any number of times (possibly zero times)**.
25+
26+
 
27+
Example 1:
28+
29+
```
30+
Input: s = "ca"
31+
Output: 2
32+
Explanation: You can't remove any characters, so the string stays as is.
33+
```
34+
35+
Example 2:
36+
37+
```
38+
Input: s = "cabaabac"
39+
Output: 0
40+
Explanation: An optimal sequence of operations is:
41+
- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
42+
- Take prefix = "a" and suffix = "a" and remove them, s = "baab".
43+
- Take prefix = "b" and suffix = "b" and remove them, s = "aa".
44+
- Take prefix = "a" and suffix = "a" and remove them, s = "".
45+
```
46+
47+
Example 3:
48+
49+
```
50+
Input: s = "aabccabba"
51+
Output: 3
52+
Explanation: An optimal sequence of operations is:
53+
- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
54+
- Take prefix = "b" and suffix = "bb" and remove them, s = "cca".
55+
```
56+
57+
 
58+
**Constraints:**
59+
60+
61+
62+
- `1 <= s.length <= 105`
63+
64+
- `s` only consists of characters `'a'`, `'b'`, and `'c'`.
65+
66+
67+
68+
## Solution
69+
70+
```javascript
71+
/**
72+
* @param {string} s
73+
* @return {number}
74+
*/
75+
var minimumLength = function(s) {
76+
var left = 0;
77+
var right = s.length - 1;
78+
while (left < right && s[left] === s[right]) {
79+
while (s[left] === s[left + 1] && left + 1 < right) left++;
80+
while (s[right] === s[right - 1] && right - 1 > left) right--;
81+
left++;
82+
right--;
83+
}
84+
return right - left + 1;
85+
};
86+
```
87+
88+
**Explain:**
89+
90+
nope.
91+
92+
**Complexity:**
93+
94+
* Time complexity : O(n).
95+
* Space complexity : O(0).

0 commit comments

Comments
 (0)