To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example, loading and being are stored as showed in Figure 1.

Figure 1
You are supposed to find the starting position of the common suffix (e.g. the position of i in Figure 1).
Input Specification:
Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positive N (≤105), where the two addresses are the addresses of the first nodes of the two words, and N is the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by −1.
Then N lines follow, each describes a node in the format:
Address Data Next
whereAddress is the position of the node, Data is the letter contained by this node which is an English letter chosen from { a-z, A-Z }, and Next is the position of the next node.
Output Specification:
For each case, simply output the 5-digit starting position of the common suffix. If the two words have no common suffix, output -1instead.
Sample Input 1:
11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010
Sample Output 1:
67890
Sample Input 2:
00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1
Sample Output 2:
-1
import java.util.Scanner;
public class Main {
/**
* 到牛客网提交,不然会有一组数据超时
*
* */
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int startA = scanner.nextInt(), startB = scanner.nextInt(), n = scanner.nextInt();
scanner.nextLine();
Node1032[] linked = new Node1032[100000 + 11];
for (int i = 0; i < n; ++i) {
String[] inputStrings = scanner.nextLine().split("\\s+");
int address = Integer.parseInt(inputStrings[0]);
int next = Integer.parseInt(inputStrings[2]);
Node1032 tempNode = new Node1032();
tempNode.address = address;
tempNode.data = inputStrings[1];
tempNode.next = next;
linked[address] = tempNode;
}
scanner.close();
boolean tag = false;
int resultAddress = -1;
while(startA!=-1) {
linked[startA].flag = true;
startA = linked[startA].next;
}
while(startB!=-1) {
if (linked[startB].flag==true) {
resultAddress = startB;
tag = true;
break;
}
startB = linked[startB].next;
}
if (tag) {
System.out.printf("%05d\n", resultAddress);
} else {
System.out.println(resultAddress);
}
}
}
class Node1032 {
Integer address;
String data;
Integer next;
boolean flag;
}

这篇博客探讨了一种使用链接列表存储英文单词的方法,通过共享相同后缀的节点来节省空间。文章给出了输入和输出规范,并提供了两个示例,解释如何找到共享后缀的起始位置。对于每个测试用例,输入包含两个单词的起始节点地址和节点总数,输出则是共同后缀的起始位置。
151

被折叠的 条评论
为什么被折叠?



