如何解决超时问题?

时间:2020-02-09 11:48:29

标签: java

我正在尝试执行此代码,但是它显示超时错误,而如果我将相同的逻辑应用于c ++,则会完美执行。

有人可以帮我吗?

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    Stack<String> s = new Stack<>();
    int q = sc.nextInt();
    int n;
    String str = "";
    s.push(str);
    while (q != 0) {
        n = sc.nextInt();
        if (n == 1) {
            str += sc.nextLine().trim();

            s.push(str);
        } else if (n == 2) {
            str = str.substring(0, str.length() - sc.nextInt());
            s.push(str);
        } else if (n == 3) {
            System.out.println(str.charAt(sc.nextInt() - 1));
        } else {
            s.pop();
            str = s.peek();
        }
        q--;
    }

}

1 个答案:

答案 0 :(得分:0)

您的代码需要进行很多验证,例如

  1. poppeek之前检查堆栈的大小。
  2. 在调用字符串substringcharAt之前,请检查字符串的长度。

除此之外,在循环中要求输入nextInt类型时,您不应依赖int。查看我的answer了解更多详细信息。

此外,通常建议打印一些文本以阐明您要输入的类型。

您尚未提及您的业务需求,因此,我已在下面给出的代码中解决了上述问题:

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Stack<String> s = new Stack<String>();
        int q = getInt(sc);
        int n, x;
        String str = "";
        s.push(str);
        while (q != 0) {
            n = getInt(sc);
            if (n == 1) {
                System.out.print("Enter a string: ");
                str += sc.nextLine().trim();
                s.push(str);
            } else if (n == 2) {
                x = getInt(sc);
                if (str.length() >= x) {
                    str = str.substring(0, str.length() - x);
                    s.push(str);
                }
            } else if (n == 3) {
                x = getInt(sc);
                if (str.length() >= x) {
                    System.out.println(str.charAt(x - 1));
                }
            } else {
                if (s.size() > 0) {
                    s.pop();
                }
                if (s.size() > 0) {
                    str = s.peek();
                }
            }
            q--;
        }
    }

    static int getInt(Scanner in) {
        boolean valid = true;
        int n = 0;
        do {
            System.out.print("Enter an integer: ");
            try {
                n = Integer.parseInt(in.nextLine());
            } catch (NumberFormatException e) {
                System.out.print("This is an invalid input");
                valid = false;
            }
        } while (!valid);
        return n;
    }
}

示例运行:

Enter an integer: 123
Enter an integer: 5
Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
Enter an integer: 1
Enter a string: hello
Enter an integer: 5
Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
e
Enter an integer: 5
Enter an integer: 

如有任何疑问,请随时发表评论。