|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static int[] failure; |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + |
| 10 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + |
| 12 | + int T = Integer.parseInt(br.readLine()); |
| 13 | + |
| 14 | + StringBuilder sb = new StringBuilder(); |
| 15 | + |
| 16 | + while(T --> 0) { |
| 17 | + ArrayList<Integer> list = new ArrayList<>(); |
| 18 | + HashMap<Character, Integer> map = new HashMap<>(); |
| 19 | + |
| 20 | + char[] A = br.readLine().toCharArray(); |
| 21 | + char[] W = br.readLine().toCharArray(); |
| 22 | + char[] S = br.readLine().toCharArray(); |
| 23 | + int aLength = A.length; |
| 24 | + for(int i = 0; i < aLength; i++) { |
| 25 | + map.put(A[i], i); |
| 26 | + } |
| 27 | + failure = new int[W.length]; |
| 28 | + |
| 29 | + failureFunction(W); |
| 30 | + |
| 31 | + for(int i = 0; i < aLength; i++) { |
| 32 | + if(i != 0) { |
| 33 | + for(int j = 0; j < S.length; j++) { |
| 34 | + S[j] = A[(map.get(S[j]) + 1) % aLength]; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if(kmp(S, W)) { |
| 39 | + list.add(i == 0 ? i : aLength - i); |
| 40 | + } |
| 41 | + } |
| 42 | + if(list.size() == 0) { |
| 43 | + sb.append("no solution").append("\n"); |
| 44 | + } else if(list.size() == 1) { |
| 45 | + sb.append("unique: ").append(list.get(0)).append("\n"); |
| 46 | + } else { |
| 47 | + Collections.sort(list); |
| 48 | + sb.append("ambiguous: "); |
| 49 | + for(int li : list) sb.append(li).append(" "); |
| 50 | + sb.append("\n"); |
| 51 | + } |
| 52 | + } |
| 53 | + System.out.println(sb); |
| 54 | + } |
| 55 | + |
| 56 | + public static void failureFunction(char[] pattern) { |
| 57 | + |
| 58 | + int pIdx = 0; |
| 59 | + |
| 60 | + for(int i = 1; i < pattern.length; i++) { |
| 61 | + |
| 62 | + while(pIdx != 0 && pattern[pIdx] != pattern[i]) |
| 63 | + pIdx = failure[pIdx - 1]; |
| 64 | + |
| 65 | + if(pattern[pIdx] == pattern[i]) { |
| 66 | + failure[i] = ++pIdx; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + public static boolean kmp(char[] s, char[] pattern) { |
| 72 | + int pIdx = 0; |
| 73 | + int max = 0; |
| 74 | + // ABCBBABC |
| 75 | + // ABC |
| 76 | + // |
| 77 | + for(int i = 0; i < s.length; i++) { |
| 78 | + |
| 79 | + while(pIdx != 0 && pattern[pIdx] != s[i]) |
| 80 | + pIdx = failure[pIdx - 1]; |
| 81 | + |
| 82 | + if(pattern[pIdx] == s[i]) { |
| 83 | + if(pIdx == pattern.length - 1) { |
| 84 | + max++; |
| 85 | + pIdx = failure[pIdx]; |
| 86 | + } else { |
| 87 | + pIdx++; |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return max == 1; |
| 93 | + } |
| 94 | + |
| 95 | +} |
| 96 | +``` |
0 commit comments