0
import java.util.*;
public class Hello {
    public static void undoOper(String str) {
        List<Character> lis = new ArrayList<>();
        char[] arr = str.toCharArray();
        for (char ch : arr) {
            lis.add(ch);
        }
        for (int i = 0; i < lis.size(); i++) {
            if (lis.get(i) == '^') {
                lis.remove(i);
                lis.remove(i - 1);
                i = i - 2;
            }
        }
        if (lis.size() == 0)
            System.out.print("-1");
        for (int i = 0; i < lis.size(); i++) {
            System.out.print(lis.get(i));
        }

        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        String[] str = new String[N];
        for (int i = 0; i < N; i++) {
            str[i] = sc.nextLine();
        }
        for (int i = 0; i < N; i++) {
            undoOper(str[i]);
        }
    }
}

This program is for undo operation The program accept N string values. The character ^ represents undo action to clear the last previous character.

Input:

Hey ^goooo^^glee^
ora^^nge^^^^

Output:

Hey google
-1(since all char gets erased)

My output:

-1
Hey google
ernest_k
  • 39,584
  • 5
  • 45
  • 86
dan
  • 1
  • 1
    You are actually calling `undoOper()` for an empty `String`, and then you call it for "Hey ^goooo^^glee^". Add `sc.nextLine();` before the first loop. – Eran Dec 31 '19 at 08:44
  • Your input throws exception, because `nextInt()` doesn't like the token `Hey` – Andreas Dec 31 '19 at 08:47
  • @Andreas i'm assuming the OP also entered 2 as the first input, and forgot to mention that (given the reported output). – Eran Dec 31 '19 at 08:48
  • 1
    @Eran I agree with your assumption, but that doesn't mean that the question is a good question. In programming, accuracy of what you write matters, since a computer will do what you say, not what you mean. People should apply that same precision of expression when asking programming questions here. We can all guess, but we shouldn't need to, so I was pointing out to OP that the question needs improvement. Can't expect improvement without letting OP know. – Andreas Dec 31 '19 at 08:53

1 Answers1

0
final static Pattern pattern = Pattern.compile("\\^", Pattern.MULTILINE);

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt(); //because \n is appended with previous nextInt
        sc.nextLine();
        String[] outPut = new String[N];
        for (int i = 0; i < outPut.length; i++) {
            String input = sc.nextLine();
            Matcher matcher = pattern.matcher(input);
            input = matcher.replaceAll("");
            outPut[i] = input;
        }
        sc.close();
        System.out.println(Arrays.asList(outPut));
    }

See if this helps you

Hades
  • 4,315
  • 3
  • 16
  • 33