Skip to content

Commit

Permalink
feat: add solutions to leetcode problem: No.1047
Browse files Browse the repository at this point in the history
  • Loading branch information
yanglbme committed Mar 9, 2021
1 parent 9ff99f4 commit 45e286b
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,52 @@

<!-- 这里可写通用的实现逻辑 -->

栈实现。

遍历字符串 S 中的每个字符 s,若栈为空或者栈顶值不等于字符 s,s 入栈,否则栈顶元素出栈。

最后返回栈中元素所组成的字符串。

<!-- tabs:start -->

### **Python3**

<!-- 这里可写当前语言的特殊实现逻辑 -->

```python

class Solution:
def removeDuplicates(self, S: str) -> str:
res = []
for s in S:
if not res or res[-1] != s:
res.append(s)
else:
res.pop()
return ''.join(res)
```

### **Java**

<!-- 这里可写当前语言的特殊实现逻辑 -->

```java

class Solution {
public String removeDuplicates(String S) {
StringBuilder sb = new StringBuilder();
int top = -1;
for (int i = 0, n = S.length(); i < n; ++i) {
char s = S.charAt(i);
if (top == -1 || sb.charAt(top) != s) {
sb.append(s);
++top;
} else {
sb.deleteCharAt(top);
--top;
}
}
return sb.toString();
}
}
```

### **...**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,37 @@ For example, in &quot;abbaca&quot; we could remove &quot;bb&quot; since the lett
### **Python3**

```python

class Solution:
def removeDuplicates(self, S: str) -> str:
res = []
for s in S:
if not res or res[-1] != s:
res.append(s)
else:
res.pop()
return ''.join(res)
```

### **Java**

```java

class Solution {
public String removeDuplicates(String S) {
StringBuilder sb = new StringBuilder();
int top = -1;
for (int i = 0, n = S.length(); i < n; ++i) {
char s = S.charAt(i);
if (top == -1 || sb.charAt(top) != s) {
sb.append(s);
++top;
} else {
sb.deleteCharAt(top);
--top;
}
}
return sb.toString();
}
}
```

### **...**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
class Solution {
public String removeDuplicates(String S) {
char[] cs = new char[S.length()];
StringBuilder sb = new StringBuilder();
int top = -1;
for (char c : S.toCharArray()) {
if (top >= 0 && c == cs[top]) {
--top;
for (int i = 0, n = S.length(); i < n; ++i) {
char s = S.charAt(i);
if (top == -1 || sb.charAt(top) != s) {
sb.append(s);
++top;
} else {
cs[++top] = c;
sb.deleteCharAt(top);
--top;
}
}
return String.valueOf(cs, 0, top + 1);
return sb.toString();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Solution:
def removeDuplicates(self, S: str) -> str:
res = []
for s in S:
if not res or res[-1] != s:
res.append(s)
else:
res.pop()
return ''.join(res)

0 comments on commit 45e286b

Please sign in to comment.