I am trying to execute this code but it shows the timeout error while the same logic if I applies with the c++ then is executes perfectly.
Can anyone help me out??
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--;
}
}
I am trying to execute this code but it shows the timeout error while the same logic if I applies with the c++ then is executes perfectly.
Can anyone help me out??
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--;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.