import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static ArrayList<String> list ;
static ArrayList<String> command ;
static int cursor;
static void backCursor() {
if(cursor==0)
return;
cursor--;
}
static void forwardCursor() {
if(cursor>=list.size())
return;
cursor++;
}
static void delete() {
if(cursor==0)
return;
list.remove(--cursor);
}
static void addChar(String string) {
list.add(cursor, string);
cursor++;
}
static void doCommand() {
for(int i=0; i<command.size();i++)
{
if(command.get(i).equals("L"))
backCursor();
if(command.get(i).equals("D"))
forwardCursor();
if(command.get(i).equals("B"))
delete();
if(command.get(i).split(" ")[0].equals("P"))
addChar(command.get(i).split(" ")[1]);
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
int N = Integer.parseInt(reader.readLine());
list = new ArrayList<String>();
command = new ArrayList<String>();
cursor = str.length();
for (int i = 0; i <N; ++i)
{
command.add(reader.readLine());
}
for (int i = 0; i <str.length(); ++i)
list.add(Character.toString(str.charAt(i)));
doCommand();
System.out.println(list.toString().replace("[","").replace("]","").replace(", ", ""));
}
}
시간초과 나옴.....ㅠㅠ흐규흐규
LinkedList를 사용한다고 해도 찾아가서 처리하기때문에 O(n)의 시간 복잡도를 가지게 되어 그런거 같다. 더 짧은 시간복잡도가 필요한 문제
교수님 자료의 도움으로
ListIterator를 사용한다면 좀 더 효율적인것을 알게되었다.
-----------------수정------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
LinkedList<Character> list = new LinkedList<>();
for (char c : s.toCharArray())
list.add(c);
int N = Integer.parseInt(reader.readLine());
ListIterator<Character> iterator = list.listIterator(list.size());
for (int i = 0; i < N; ++i) {
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
String cmd = tokenizer.nextToken();
switch (cmd) {
case "L":
if (iterator.hasPrevious())
iterator.previous();
break;
case "D":
if (iterator.hasNext()) //
iterator.next();
break;
case "B":
if (iterator.hasPrevious()) {
iterator.previous();
iterator.remove();
}
break;
case "P":
iterator.add(tokenizer.nextToken().charAt(0));
break;
}
}
StringBuilder builder = new StringBuilder();
for (char c : list)
builder.append(c);
System.out.println(builder.toString());
}
}
list.listIterator(list.size());
boolean hasNext()
boolean hasPrevious()
Object next()
Object previous()
void remove()
void set(Object o)
int nextIndex()
int previousIndex()
void add(Object o)
검색해보니까 LinkedList보다 Stack을 이용해도 해결 가능하다고 한다.