首页 > 试题广场 >

字符串的相邻字符去重

[编程题]字符串的相邻字符去重
  • 热度指数:1596 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个仅由英文小写字母组成的字符串s,将相邻且相同的两个字符删掉构成新的字符串,重复删除操作直至生成不符合删除条件的字符串并返回。

示例1

输入

"bcaac"

输出

"b"

说明

bcaac执行删除操作后变为bcc,再次执行删除操作变为b,此时不再符合删除条件故返回b。   
示例2

输入

"ab"

输出

"ab"

说明

原串即不符合删除条件,故直接返回。   
示例3

输入

"bcaaac"

输出

"bcac"

说明

bcaaac执行删除操作后变为 bcac ,此时不再符合删除条件 
package main
import "strings"

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return string字符串
*/
func removeDuplicates( s string ) string {
    stk:=[]string{}
    for _,ch:=range s{
        if len(stk)>0&&stk[len(stk)-1]==string(ch){
            stk=stk[:len(stk)-1]
        }else{
            stk=append(stk,string(ch))
        }
    }
    return strings.Join(stk,"")
}

发表于 2023-03-09 11:57:22 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return string字符串
     */
    public String removeDuplicates (String s) {
        // write code here
        Stack<Character> stack = new Stack<Character>();//构造字符串栈,该栈内元素不重复
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {//从左往右遍历
            char a = s.charAt(i);//当前字符
            if (!stack.isEmpty() && stack.peek() == a) {//如果当前字符与栈顶字符相等,即两两重复,栈顶元素抛出
                stack.pop();
            } else {//当字符不两两重复时才入栈
                stack.push(a);
            }
        }
        while (!stack.isEmpty()) {//从栈顶开始抛出元素,因为栈是先进后出,所以得到的目标字符串是反过来的
            char b = stack.pop();
            sb.append(b);
        }
        return sb.reverse().toString();
    }
}

发表于 2024-03-20 17:42:30 回复(0)
public String removeDuplicates (String s) {
    // write code here
    int len = s.length();
    Stack<Character> stack = new Stack();
    for (int i = 0; i < len; i++) {
        if (stack.isEmpty()) {
            stack.push(s.charAt(i));
        } else {
            if (stack.peek() == s.charAt(i)) {
                stack.pop();
            } else {
                stack.push(s.charAt(i));
            }
        }
    }
    if (stack.isEmpty()) {
        return "";
    } else {
        StringBuffer sb = new StringBuffer();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }
}

发表于 2022-08-28 15:16:40 回复(0)
//使用char数组模拟栈,提升空间和时间性能
int index = -1;
        char[] chs = new char[s.length()];
        for (int i = 0; i < s.length(); i++) {
            if(index != -1 && chs[index] == s.charAt(i)) {
                index--;
            }else {
                chs[++index] = s.charAt(i);
            }
        }
        return new String(chs, 0, index + 1);
发表于 2022-08-27 19:09:02 回复(0)
 string removeDuplicates(string s) {
        // write code here
        string ans;
        stack<char>st;
        st.push(s[0]);
        for(int i=1;i<s.size();i++){
            if((!st.empty())&&st.top()==s[i]) {st.pop(); continue;}
            st.push(s[i]);
        }
        while(!st.empty()){
            ans+=st.top(); 
            st.pop();
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
发表于 2022-07-09 15:17:06 回复(0)
class Solution:
    def removeDuplicates(self , s: str) -> str:
        # write code here
        stack = []
        for x in s:
            if not stack&nbs***bsp;stack[-1] != x:
                stack.append(x)
            else:
                stack.pop()
        return ''.join(stack)

发表于 2022-07-08 23:14:48 回复(0)
class Solution:
    def removeDuplicates(self , s: str) -> str:
        # write code here
        res = ''
        for ch in s:
            if res == '':
                res += ch
            elif ch == res[-1]:
                res = res[:-1]
            else:
                res += ch
        return res

发表于 2022-04-22 15:35:33 回复(0)
#coding:utf-8
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#

# @param s string字符串 
# @return string字符串
#
class Solution:
    def removeDuplicates(self , s ):
        # write code here
        c=0
        b=1
        while b!=c:
            b=c
            for i in range(len(s)-1):
                if s[i]==s[i+1]:
                    s=s[:i]+s[i+2:]
                    c+=1
                    break
                           
        return s
            
            
发表于 2022-04-10 01:14:26 回复(0)

问题信息

难度:
8条回答 1795浏览

热门推荐

通过挑战的用户

查看代码