【发布时间】:2020-08-29 06:01:57
【问题描述】:
问题陈述来自hackerrank。
名称: 简单文本编辑器
描述: 我取了一个 stackNode.in stackNode 我使用了三个变量 top 是为之前执行的操作操作是 k 和 s用于存储在先前操作中删除或附加的字符串。
问题链接 :https://www.hackerrank.com/challenges/simple-text-editor/problem?isFullScreen=false
import java.io.*;
import java.util.*;
class StackNode
{
int top;
int operat;
String s;
}
public class Solution
{
static String S="";
static Stack<StackNode> stack=new Stack<>();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- >0)
{
int operation=sc.nextInt();
if(operation == 1)
{
String st=sc.next();
S=S+st;
StackNode node=new StackNode();
node.top=operation;
node.s=st;
stack.push(node);
}
else
if(operation == 2)
{
int k=sc.nextInt();
delete(k,operation);
}
else
if(operation == 3)
{
int k=sc.nextInt();
print(k);
}
else
if(operation == 4)
undo();
}
}
static void delete(int k,int operation)
{
StackNode node=new StackNode();
node.top=operation;
node.operat=k;
if(S.length() < k)
{
node.s=S;
S="";
return;
}
else
{
node.s=S.substring(S.length()-k);
S=S.substring(0,S.length()-k);
}
stack.push(node);
}
static void print(int k)
{
if(k<=S.length())
System.out.println(S.charAt(k-1));
}
static void undo()
{
if(stack.isEmpty())
return;
StackNode node=stack.pop();
if(node.top == 1)
{
S=S.substring(0,S.length()-node.s.length());
}
else
if(node.top == 2)
{
S=S+node.s;
}
}
}
【问题讨论】:
-
顺便说一句,
java.util.Stack已经过时了。我会使用ArrayList或ArrayDeque作为堆栈。 超过时间限制可能没有区别。对于轻微的优化,不要存储附加的字符串,只存储它的长度,这足以撤消附加。
标签: java string object time stack