首页 > 试题广场 >

吐泡泡

[编程题]吐泡泡
  • 热度指数:6989 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}小鱼儿会吐出两种泡泡:大泡泡 \texttt{,小泡泡 \texttt{;两种泡泡的变化规则如下:
\hspace{23pt}\bullet\,任意两个相邻的小泡泡会融合成一个大泡泡;
\hspace{23pt}\bullet\,任意两个相邻的大泡泡会相互爆炸,变成空白(即消失)。
\hspace{15pt}上述合并与爆炸过程自左至右依次进行,直至无法再进行任何操作。

\hspace{15pt}例如,对于初始泡泡序列 \texttt{,经过一段时间后会变成 \texttt{


输入描述:
\hspace{15pt}第一行输入一个整数 T\left(1\leqq T\leqq 10\right) 代表数据组数。
\hspace{15pt}接下来 T 行,每行一个仅由 'O' 和 'o' 构成的字符串 s,字符串长度不超过 10^5


输出描述:
\hspace{15pt}每组输出仅包含一行,输出一行字符串代表小鱼儿吐出的泡泡经过融合以后所剩余的泡泡。
示例1

输入

1
ooOOoooO

输出

oO

说明


示例2

输入

1
OOOOOOOOOOOOOOOooooooooooooooooooOOoOoOoOOOoOoOoOOoOooOoOOoOoOoOoOoOoOoOoOoOooOoOoOOoooOOOOoOOoooOOoOOOOOooOoOOOoOOoooOoOOOooOooooOoOooOoOooOoOooOoOOOOOOOOOOOOOOoOoOoOooOOoOooOoOOoOoOOOOooooOOOOOooooooOOOOOOoooooOoOooOoOoOoooOoOOOOoOoOoOOOOOOOOOOoOooOoOooOOoOOoOooOooOOoooOOOoOoOooOOooOoOOOoOOoOOOoOooOoOOOooOOoooOOoOOoOooOOOOoOooOoOoOoOooOoOoO

输出

oOoOoOoOoOoO

说明



备注:

n = int(input())
for _ in range(n):
    li, a = list(input().strip()), []
    for i in li:
        if i == "o":
            if a and a[-1] == "o":
                a.pop()
                a.pop() if a and a[-1] == "O" else a.append("O")
            else:
                a.append(i)
        elif i == "O":
            a.pop() if a and a[-1] == "O" else a.append(i)
        else:
            a.append(i)
    print("".join(a))
发表于 2025-11-14 16:07:45 回复(0)
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int round = in.nextInt();
        // 处理多组测试用例
        for (int i = 0; i < round; i++) {
            String str = in.next();
            System.out.println(bubble(str));
        }
        in.close();
    }

    public static String bubble(String str) {
        Stack<Character> stack = new Stack<>();
        
        for (int i = 0; i < str.length(); i++) {
            char current = str.charAt(i);
            // 循环处理当前字符与栈顶的反应(可能产生连续反应)
            while (!stack.isEmpty()) {
                char top = stack.peek();
                // 两个小泡泡融合成大泡泡
                if (top == 'o' && current == 'o') {
                    stack.pop(); // 弹出栈顶的'o'
                    current = 'O'; // 融合后变成大泡泡,继续检查是否与新栈顶反应
                } 
                // 两个大泡泡爆炸消失
                else if (top == 'O' && current == 'O') {
                    stack.pop(); // 弹出栈顶的'O'
                    current = 0; // 爆炸后消失,用0标记无需入栈
                    break; // 已爆炸,无需继续检查
                } 
                // 其他情况(不反应),退出循环
                else {
                    break;
                }
            }
            // 如果当前字符未消失(不是爆炸后的状态),则入栈
            if (current != 0) {
                stack.push(current);
            }
        }
        
        // 转换栈为字符串
        return stackToString(stack);
    }

    // 栈转字符串工具方法
    public static String stackToString(Stack<Character> stack) {
        StringBuilder sb = new StringBuilder();
        for (Character c : stack) {
            sb.append(c);
        }
        return sb.toString();
    }
}



发表于 2025-07-31 17:47:55 回复(0)
#include <math.h>
#include <stdio.h>

int main() {
    int T;
    scanf("%d",&T);
    getchar();
    for(int i=0;i<T;i++){
        int s;
        static char stack[100000];
        int top =-1;
        while ((s=getchar())!='\n'&&s!=EOF) {
        switch (s) {
            case 'o':
            stack[++top]=s;
             while (top >= 1 && stack[top] == 'o' && stack[top-1] == 'o') {
                        stack[top-1] = 'O';
                        top--;
            }
             while (top >= 1 && stack[top] == 'O' && stack[top-1] == 'O') {
            top -= 2;
            }
            break;
            case 'O':
            stack[++top]=s;
            while (top >= 1 && stack[top] == 'O' && stack[top-1] == 'O') {
            top -= 2;
            }
            while (top >= 1 && stack[top] == 'o' && stack[top-1] == 'o') {
                        stack[top-1] = 'O';
                        top--;
            }
            break;
            }
        }
        stack[top+1]='\0';
        printf("%s\n",stack);
    }
    return 0;
}
发表于 2025-11-22 17:39:42 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        stack<char> sta;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == 'o') {
                if (!sta.empty() && sta.top() == 'o') {
                    sta.pop();
                    if (!sta.empty() && sta.top() == 'O') {
                        sta.pop();
                    } else {
                        sta.push('O');
                    }
                } else {
                    sta.push('o');
                }
            } else {
                if (!sta.empty() && sta.top() == 'O') {
                    sta.pop();
                } else {
                    sta.push('O');
                }
            }
        }
        string result = "";
        while (!sta.empty()) {
            result = sta.top() + result;
            sta.pop();
        }
        cout << result << endl;
    }
    return 0;
}
发表于 2025-11-09 20:55:12 回复(0)
#include <stdio.h>
#include <string.h>
//返回原串偏移指针,该指针到字符串结束存储结果字符串
char * bubbles(char *str){
    char *rus_str = str;
    int top;

    int i = 0;
    while (rus_str[i] != '\0') {
        //与后一个字符是否相同
        if(rus_str[i] == rus_str[i+1]){
            //i和i+1均是'o'则i+1更新为'O',0~i-1后移一位(1~i)字符串变短,
            //则rus_str向后偏移一位
            if(rus_str[i] == 'o'){
                rus_str[i+1] = 'O';
                for (int j = i; j > 0; j--) {
                    rus_str[j] = rus_str[j-1];
                }
                rus_str++;
            }
            //i和i+1均是'o'则i+1更新为'O',0~i-1后移两位(2~i+1)字符串变短,
            //则rus_str向后偏移两位
            else {
                for (int j = i+1; j > 1; j--) {
                    rus_str[j] = rus_str[j-2];
                }
                rus_str += 2;
            }
            //字符串更新后需从头开始索引清零
            i = 0;
        }
        else i++;
    }
    return rus_str;
}
int main() {
    int n;
    char str[100001], rus_str[100001];

    scanf("%d\n", &n);
    while (n--) {
        scanf("%s", str);
        printf("%s\n", bubbles(str));
    }
    return 0;
}

发表于 2025-11-05 15:27:30 回复(0)
不知道为什么我这个输出队尾打印才
import java.util.Scanner; 

import java.util.ArrayDeque;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n =in.nextInt();
        for (int i=0; i<n; i++) {
            String str = in.next();
            ArrayDeque<Character> deque = new ArrayDeque<Character>();
            for (char c:str.toCharArray()) {
                if (deque.isEmpty()) {
                        deque.push(c);
                        continue;
                }
                if (c=='o' && deque.getFirst()=='o') {
                    deque.pop();
                    if (deque.isEmpty()) {
                        deque.push('O');
                        continue;
                    }
                    if (deque.getFirst()=='O') {
                        deque.pop();
                    }
                } else if (c=='O' && deque.getFirst()=='O') {
                    deque.pop();
                } else {
                    deque.push(c);
                }
            }
            while (!deque.isEmpty()) {
                System.out.print(deque.removeLast());
            }
            System.out.println();
        }    
    }
}

能过
发表于 2025-10-22 10:01:12 回复(0)
每次 先替换’oo‘,再替换’OO‘,直至字符串中没有’oo‘和’OO‘,为什么结果不一样?
发表于 2025-09-15 18:27:01 回复(0)
#include<bits/stdc++.h>
using namespace std;
int main(){
  string s;
 int m;
 cin>>m;
 while(m--){
  while(cin>>s){
    stack<char> st;
     int n=s.length();
    if(n==1) cout<<s;
    else{
      for(int i=0;i<n;i++){
        if(st.empty()){
          st.push(s[i]);
        }
        else{
          if(s[i]==st.top()){
            if(s[i]=='o'){
              st.pop();
              if(st.empty()){
                st.push('O');
              }
            else {
                if(st.top()=='O'){
                  st.pop();
                }
                else{
                  st.push('O');
                }
              }
            }
            else{
              st.pop();
            }
          }
          else st.push(s[i]);
        }
      }
      stack<char>st1;
      while(!st.empty()){
        st1.push(st.top());
        st.pop();
      }
      while(!st1.empty()){
        cout<<st1.top();
        st1.pop();
      }
    }
      cout<<endl;
  }

 }
    return 0;
}
发表于 2025-09-13 19:48:22 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        for(int i=0;i<T;i++){
            String str = in.next();
            Deque<Character> stack = new ArrayDeque<>();
            for(char c : str.toCharArray()){
                char cur = c;
                while(!stack.isEmpty()){
                    char top = stack.peek();
                    if(top=='o' && cur=='o'){
                        stack.pop();
                        cur = 'O';
                    }else if(top =='O' && cur == 'O'){
                        stack.pop();
                        cur = 0;
                        break;
                    }else{
                        break;
                    }
                }
                if(cur!=0){
                    stack.push(cur);
                }
            }
            StringBuilder sb = new StringBuilder();
            for(char c : stack){
                sb.append(c);
            }
            for(int j=sb.length()-1;j>=0;j--){
                System.out.print(sb.charAt(j));
            }
            System.out.println();
        }
        in.close();
    }
}
发表于 2025-08-10 14:28:24 回复(0)
T = int(input())
for _ in range(T):
    s = list(map(str, input().strip()))
    s_new = []
    for i in s:
        if i == 'o' :
            if s_new and s_new[-1] == 'o':
                s_new.pop()  # 弹出前一个'o'
                #两个‘o’合并成‘O’,并尝试和栈顶的‘O’抵消(重要)
                if s_new and s_new[-1] =='O':
                    s_new.pop()
                else:
                    s_new.append('O')
            else:
                s_new.append('o')
        elif i == 'O':
            if s_new and s_new[-1] == 'O':
                s_new.pop()  # 'O' 和 'O' 抵消
            else:
                s_new.append('O')
        else:
            s_new.append(i)
    print(''.join(map(str, s_new)))


d第一次提交的时候,当前面的O是2个o合并的,再入栈一个O时,会直接入栈O,导致存在2个O没有抵消的情况发生,所以在2个o合并的过程中增加一个步骤,进行取栈顶操作。
发表于 2025-08-06 11:26:24 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    string ss;
    for(int i=0;i<n;i++){
        vector<char> c;
        stack<char> s;
        cin >> ss;
        for (int j=0;j<ss.size();j++){
            if(ss[j]=='o'){
                if(s.empty() || s.top()!='o'){
                    s.push(ss[j]);
                }else if(s.top() == 'o'){
                    s.pop();
                    if( s.size()!=0 && s.top()=='O'){
                        s.pop();
                    }else{
                        s.push('O');
                    }
                }
            }
            else if(ss[j]=='O'){
                if(s.empty() || s.top()!='O'){
                    s.push(ss[j]);
                }else if(s.top() == 'O'){
                    s.pop();
                }
            }

        }
        while (!s.empty()) {
        c.push_back(s.top());
        s.pop();
        }
        for(int i=c.size()-1;i>=0;i--){
        cout << c[i];
        }
        cout << endl;
    }
}
// 64 位输出请用 printf("%lld")

发表于 2025-07-28 21:43:46 回复(0)
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            in.nextLine();
            for(int k = 0;k < n;k++){
                String a = in.nextLine();
                char[] str = a.toCharArray();
                Deque<Character> stack = new ArrayDeque<>();
                for(char i:a.toCharArray()){
                    if(stack.isEmpty()){
                        stack.push(i);
                    }else{
                        if(i == 'o' && stack.peek() == 'o'){
                            stack.pop();
                            if(stack.isEmpty()){
                                stack.push('O');
                            }else{
                                stack.pop();
                            }
                        }else if(i == 'O' && stack.peek() == 'O'){//注意,这™是O不是0,找半天错误了
                            stack.pop();
                        }else{
                            stack.push(i);
                        }
                       
                    }
                }
                StringBuilder output = new StringBuilder();
                while(!stack.isEmpty()){
                    output.append(stack.pop());
                }
                System.out.println(output.reverse());
            }
           
        }
    }
}
发表于 2025-07-10 22:09:05 回复(0)
T = int(input())

for _ in range(T):
    data = input()
    stack = ["1"]
    for i in range(len(data)):
        if stack[-1]==data[i]=="o":
            stack.pop()
            stack.append("O")
            if stack[-1]==stack[-2]:
                stack.pop()
                stack.pop()
        elif stack[-1]==data[i]=="O":
            stack.pop()
        else:
            stack.append(data[i])
    
    print(*stack[1::],sep="")

发表于 2025-06-22 01:43:58 回复(0)
class Stack:
    def __init__(self) -> None:
        self.items = []

    def push(self, x):
        self.items.append(x)

    def pop(self):
        if not self.is_empty():
            self.items.pop()

    def is_empty(self):
        return len(self.items) == 0

    def peek(self):  # 修正拼写
        if not self.is_empty():
            return self.items[-1]
        return None

def tu_bubbles(bubbles):
    # 初始化栈
    stack = Stack()
    # 遍历泡泡序列
    for bubble in bubbles:
        if bubble == "o":
            if stack.peek() == "o":
                stack.pop()
                if stack.peek() == "O":
                    stack.pop()
                else:
                    stack.push("O")
            else:
                stack.push("o")
        elif bubble == "O":
            if stack.peek() == "O":
                stack.pop()
            else:
                stack.push("O")
    # 输出最终结果
    return "".join(stack.items)

# 读取输入
import sys
n = int(input())
for line in sys.stdin:
    s = line.strip()
    print(tu_bubbles(s))

发表于 2025-06-10 15:13:19 回复(0)

问题信息

上传者:牛客303862号
难度:
14条回答 2125浏览

热门推荐

通过挑战的用户

查看代码
吐泡泡