非常好奇第2题的数据
用Trie树实现了一把,但是只有 50% 正确率,实在找不到原因在哪😅
有无佬帮忙看看
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new BufferedInputStream(System.in));
BufferedOutputStream outputStream = new BufferedOutputStream(System.out);
// PrintWriter writer = new PrintWriter(outputStream);
// int n = scanner.nextInt();
scanner.nextLine();
String s = scanner.nextLine();
Trie trie = new Trie();
trie.mergeString(s);
byte[] ans = new byte[s.length()];
trie.outputString(trie.root, ans, -1, outputStream);
outputStream.flush();
}
static class Node {
Node[] v = new Node[26];
boolean isResult = false;
int count = 0;
}
static class Trie {
Node root;
Trie() {
root = new Node();
}
void mergeString(String s) {
Node currentRoot = root;
int idx = 0;
int len = s.length();
boolean hasRemoved = false;
while (idx < len) {
if (idx == len - 1 || s.charAt(idx + 1) == ' ') {
if (hasRemoved) {
int c = s.charAt(idx) - 'a';
if (currentRoot.v[c] == null) {
currentRoot.v[c] = new Node();
}
currentRoot = currentRoot.v[c];
}
currentRoot.isResult = true;
currentRoot.count += 1;
idx += 2;
hasRemoved = false;
currentRoot = root;
} else {
if (s.charAt(idx) > s.charAt(idx+1) && !hasRemoved) {
// skip this char
hasRemoved = true;
} else {
// insert
int c = s.charAt(idx) - 'a';
if (currentRoot.v[c] == null) {
currentRoot.v[c] = new Node();
}
currentRoot = currentRoot.v[c];
}
idx += 1;
}
}
root.count = 0;
root.isResult = false;
}
void outputString(Node currentRoot, byte[] stack, int currentIdx, BufferedOutputStream outputStream) throws IOException {
if (currentRoot.isResult) {
// output sb
int times = 0;
while (times < currentRoot.count) {
for (int idx = 0; idx <= currentIdx; idx++) {
outputStream.write(stack[idx]);
}
times += 1;
}
}
for (int idx = 0; idx < 26; idx++) {
if (currentRoot.v[idx] != null) {
stack[++currentIdx] = (byte) ('a' + idx);
outputString(currentRoot.v[idx], stack, currentIdx, outputStream);
currentIdx--;
}
}
}
}
}
查看22道真题和解析
