求数组中各元素的最长的公共前缀
- Example 1:
- Input: ["flower","flow","flight"]
- Output: "fl"
- Example 2:
- Input: ["dog","racecar","car"]
- Output: ""
- Explanation: There is no common prefix among the input strings.
解法
- var longestCommonPrefix = function(strs) {
- if (strs.length === 0) return '';
- return strs.reduce((result, s) => {
- return longestInTwo(result, s);
- });
- };
- const longestInTwo = (a, b) => {
- let long, short;
- if (a.length> b.length) {
- long = a;
- short = b;
- } else {
- long = b;
- short = a;
- }
- while (long.indexOf(short) !== 0) {
- short = short.slice(0, -1);
- }
- return short;
- };
来源: http://www.jianshu.com/p/2b637fb9afc3