[LeetCode] 1544. Make The String Great

Given a string s of lower and upper case English letters.

A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

  • 0 <= i <= s.length - 2
  • s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

Notice that an empty string is also good.

Example 1:

Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

Example 2:

Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""

Example 3:

Input: s = "s"
Output: "s"

Constraints:

  • 1 <= s.length <= 100
  • s contains only lower and upper case English letters.

整理字符串。

给你一个由大小写英文字母组成的字符串 s 。

一个整理好的字符串中,两个相邻字符 s[i] 和 s[i+1],其中 0<= i <= s.length-2 ,要满足如下条件:

若 s[i] 是小写字符,则 s[i+1] 不可以是相同的大写字符。
若 s[i] 是大写字符,则 s[i+1] 不可以是相同的小写字符。
请你将字符串整理好,每次你都可以从字符串中选出满足上述条件的 两个相邻 字符并删除,直到字符串整理好为止。

请返回整理好的 字符串 。题目保证在给出的约束条件下,测试样例对应的答案是唯一的。

注意:空字符串也属于整理好的字符串,尽管其中没有任何字符。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/make-the-string-great
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是 stack。题意说了不能有两个相邻的字符是互为大小写的,所以当我们遍历字符串中的每一个 char 的时候,如果当前的 char 是小写字母,需要看一下之前一个字母是否是对应的大写;同样的,如果当前的 char 是大写字母,需要看一下之前一个字母是否是对应的小写。如果满足这两种情况的任意一种,则跳过当前字母的同时还需要把栈顶元素也弹出。其他情况则直接入栈。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public String makeGood(String s) {
 3         Deque<Character> queue = new ArrayDeque<>();
 4         for (char c : s.toCharArray()) {
 5             if (queue.isEmpty()) {
 6                 queue.offer(c);
 7             } else if (Character.isUpperCase(c) && Character.isLowerCase(queue.peekLast()) && Character.toLowerCase(c) == queue.peekLast()) {
 8                 queue.pollLast();
 9             } else if (Character.isLowerCase(c) && Character.isUpperCase(queue.peekLast()) && Character.toUpperCase(c) == queue.peekLast()) {
10                 queue.pollLast();
11             } else {
12                 queue.offerLast(c);
13             }
14         }
15 
16         StringBuilder sb = new StringBuilder();
17         while (!queue.isEmpty()) {
18             sb.append(queue.pollFirst());
19         }
20         return sb.toString();
21     }
22 }

 

LeetCode 题目总结

posted @ 2022-11-08 11:27  CNoodle  阅读(99)  评论(0编辑  收藏  举报