我已经完成了一项 Google Foobar 任务,并且很好奇为什么 2 个似乎等效的实现以不同的方式工作。当第二个解决方案通过所有测试用例时,第一个给我带来“测试 2 失败”。我知道他们两个都没有遵循最佳 OOP 实践,但我很感兴趣第一个实现的确切问题是什么。
1.
public class Answer {
static Map<Character, LinkedList<Character>> g = new HashMap<Character, LinkedList<Character>>();
static Set<Character> visited = new HashSet<Character>();
static ArrayList<Character> ans = new ArrayList<Character>();
public static void dfs(char v) {
visited.add(v);
//some standard code for DFS
ans.add(v);
}
public static String topologicalSort() {
for (Character element : g.keySet()) {
if (!visited.contains(element))
dfs(element);
}
//some code to prepare the output
}
public static void builGraph(String[] words) {
//some code to build adjacency list and then use it through g reference
}
public static String answer(String[] words) {
if (words.length == 1) {
//some code
}
builGraph(words);
return topologicalSort();
}
public static void main(String[] args) {
//some code
System.out.println(answer(words));
}
}
2.
public class Answer {
static Map<Character, LinkedList<Character>> g;
static Set<Character> visited;
static ArrayList<Character> ans;
public static void dfs(char v) {
visited.add(v);
//some standard code for DFS
ans.add(v);
}
public static String topologicalSort() {
visited = new HashSet<Character>();
ans = new ArrayList<Character>();
for (Character element : g.keySet()) {
if (!visited.contains(element))
dfs(element);
}
//some code to prepare the output
}
public static void builGraph(String[] words) {
g = new HashMap<Character, LinkedList<Character>>();
//some code to build adjacency list and then use it through g reference
}
public static String answer(String[] words) {
if (words.length == 1) {
//some code
}
builGraph(words);
return topologicalSort();
}
public static void main(String[] args) {
//some code
System.out.println(answer(words));
}
}