Untitled
unknown
plain_text
9 months ago
2.1 kB
8
Indexable
// User function Template for Java
import java.util.stream.Collectors;
class Solution {
private boolean isValid(int idx, String str){
return idx < str.length();
}
boolean isCyclic(int currNode, List<List<Integer>> adj, int[] nodeStates, List<Integer> ans){
if(nodeStates[currNode] == 1 || nodeStates[currNode] == 2){
return nodeStates[currNode] == 1;
}
nodeStates[currNode] = 1;
for(int letter : adj.get(currNode)){
if(isCyclic(letter, adj, nodeStates, ans)){
return true;
}
}
ans.add(currNode);
nodeStates[currNode] = 2;
return false;
}
public String findOrder(String[] words) {
// code here
List<List<Integer>> adj = new ArrayList<>();
for(int i=0; i<26; i++){
adj.add(new ArrayList<>());
}
if(words.length == 1){
} else {
for(int i=1; i<words.length; i++){
int x = 0, y = 0;
while(isValid(x, words[i-1]) && isValid(y, words[i]) && words[i-1].charAt(x) == words[i].charAt(y)){
++x;
++y;
}
if(x!=words[i-1].length() && y!=words[i].length()){
adj.get(words[i-1].charAt(x) - 'a').add(words[i].charAt(y) - 'a');
} else if(x!=words[i-1].length() && y==words[i].length()){
// System.out.println("it breaks at i: " + i);
return "";
}
}
}
List<Integer> ans = new ArrayList<>();
int[] nodeStates = new int[26];
for(String word : words){
for(int i=0; i<word.length(); i++){
if(isCyclic(word.charAt(i) - 'a', adj, nodeStates, ans)){
return "";
}
}
}
Collections.reverse(ans);
return ans.stream().map(diff -> String.valueOf((char) ('a' + diff))).collect(Collectors.joining());
}
}
Editor is loading...
Leave a Comment