Description:
Write a function to find the longest common prefix string amongst an array of strings.
解法:
暴力查找字符串集合中的相同前缀,将单词上下排好,相当于一个各行长度有可能不相等的二维数组,采用纵向逐列遍历,在遍历的过程中,如果某一行没有了,说明其为最短的单词,因为共同前缀的长度不能长于最短单词,所以此时返回已经找出的共同前缀。我们每次取出第一个字符串的某一个位置的单词,然后遍历其他所有字符串的对应位置看是否相等,如果有不满足的直接返回res,如果都相同,则将当前字符存入结果,继续检查下一个位置的字符,代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> output = new ArrayList();
helper(root,output);
return output;
}
void helper(TreeNode root,List<Integer> output){
if(root == null){
return;
}
helper(root.left,output);
helper(root.right,output);
output.add(root.val);
}
}