java - 我的一个测试用例没有通过 .Giving TLE for one case
问题描述
问题陈述来自hackerrank。
名称:简单文本编辑器
描述:我使用了一个 stackNode.in stackNode 我使用了三个变量 top 用于先前执行的操作 operation is 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;
}
}
}
解决方案
问题:当字符串很长时,在每个追加和删除操作上复制整个编辑器内容需要很长时间。解决方案:而不是将编辑器内容保留在String
使用 aStringBuffer
或StringBuilder
.
编辑器的内容可能多达一百万个字符。以下每个代码行都将此内容复制到一个新的String
:
S=S+st;
S=S.substring(0,S.length()-k);
S=S.substring(0,S.length()-node.s.length());
S=S+node.s;
StringBuffer
相反,当您从or追加或删除时StringBuilder
,操作中未涉及的字符可以保留在原处。
其他可能的轻微优化:
- 在撤消堆栈上不存储附加的字符串,而只存储它的长度。该长度足以撤消附加操作。
- 使用
switch
语句来选择正确的操作,而不是链接 if-else。
就时间复杂度和空间复杂度而言,switch和chained if-else有什么区别吗
在大多数情况下,打开一个int
值应该比链式 if-else 更快。
文档链接: StringBuilder
推荐阅读
- sql - 如何在 where 子句 Big Query 中使用 DATETIME_SUB 函数
- sql - 在 Postgres 中使用列名进行透视
- mathematical-optimization - 我有多个错误,其中一个说:“来自 IBM ILOG CPLEX 的异常:CPLEX 错误 5002:'q1' 不是凸的。->。”
- python - 如何为随时间变化的矩阵设置动画?
- flutter - Convert List of Bytes to integer value in Flutter
- swift - SwiftUI - 使用 DatePicker GraphicalDatePickerStyle 作为只读日历
- java - 如何在多线程中并行启动 Java 线程?
- php - 如何将简单的php数组转换为带头的json数据
- javascript - 编写 JS 存储 10 个值但 TypeError: input is a void element tag and must not have `children` 也不能使用 `dangerouslySetInnerHTML
- java - 无法使用java在android上发送每日通知