2015年11月15日星期日

pretty print organization

Employee,Manager,ItemsSold
Alice,,5
Bob,Alice,3. 1point 3acres 璁哄潧
Carol,Bob,2
Richard,Carol,5
Kim,Richard,5
Tom,Carol,5. 鐣欏鐢宠璁哄潧-涓€浜╀笁鍒嗗湴
David,Bob,3
Eve,Alice,2-google 1point3acres
Ferris,Eve,1
就是员工跟他的manager还有销售的item,之后输出下面的结构,数字表示该员工跟他下属的sold item总额. 1point 3acres 璁哄潧
Alice 31
|-Bob 23
| |-Carol 17
| | |-Richard 10
| | | \_Kim 5
| | \_Tom 5
| \_David 3
\_Eve 3
  \_Ferris 1
解法:这题略坑,算法就是先建图然后跑dfs,主要是output很恶心,output也是用dfs做的,当时写到最后还是差一些,这个output给大家一点参考吧,如果你的代码能输出上面那个例子,应该已经过了。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class Solution {

public static class Employee {
List<Employee> employees;

String name;
int num;

public Employee(String name) {
this.name = name;
this.employees = new ArrayList<>();
}
}

private void outputTree(List<String> input) {
HashMap<String, Employee> map = new HashMap<>();
Employee head = null;
for (String entry : input) {
String tokens[] = entry.split("\\,");
Employee employee = map.get(tokens[0]);
if (employee == null) {
employee = new Employee(tokens[0]);
map.put(tokens[0], employee);
}
employee.num = Integer.parseInt(tokens[2]);
if (tokens[1].isEmpty()) {
head = employee;
continue;
}
Employee manager = map.get(tokens[1]);
if (manager == null) {
manager = new Employee(tokens[1]);
map.put(tokens[1], manager);
}
manager.employees.add(employee);
}
updateNum(head);
print(head, "");
}

private void print(Employee emp, String prefix) {
System.out.println(prefix + "" + emp.name + " " + emp.num);
StringBuilder sb = new StringBuilder();
for (char c : prefix.toCharArray()) {
if (c == '\\') {
sb.append(' ');
} else if (c != '_' && c != '-') {
sb.append(c);
}
}
for (int i = 0; i < emp.employees.size(); i++) {
Employee emp2 = emp.employees.get(i);
if (i != emp.employees.size() - 1) {
print(emp2, sb.toString() + "|-");
} else {
print(emp2, sb.toString() + "\\_");
}
}
}

private int updateNum(Employee emp) {
int res = emp.num;
for (Employee emp2 : emp.employees) {
res += updateNum(emp2);
}
emp.num = res;
return res;
}

public static void main(String args[]) {
Solution s = new Solution();
// List<String> list = Arrays.asList("Bob,Alice,3", "Carol,Bob,2",
// "Richard,Carol,5", "Kim,Richard,5", "Tom,Carol,5",
// "David,Bob,3", "Eve,Alice,2", "Ferris,Eve,1", "Alice,,5",
// "Chen,Eve,5", "Cen,Eve,2", "Eli,Cen,1", "Baba,Cen,2", "Rui,Chen,2");
List<String> list = Arrays.asList("Bob,Alice,3", "Alice,,5","Cal,Alice,3");
// List<String> list = Arrays.asList("Alice,,5", "Bob,Alice,3",
// "Carol,Bob,2", "David,Bob,3", "Eve,Alice,2", "Ferris,Eve,1");
s.outputTree(list);
}
}

没有评论:

发表评论