Question:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example:

  1. Input: ["flower","flow","flight"]
  2. Output: "fl"
  1. Input: ["dog","racecar","car"]
  2. Output: ""
  3. Explanation: There is no common prefix among the input strings.

Solution:

  1. /**
  2. * @param {string[]} strs
  3. * @return {string}
  4. */
  5. var longestCommonPrefix = function(strs) {
  6. const start = strs[0];
  7. const result = [];
  8. let vaild = function (index) {
  9. for (let j = 1 ; j < strs.length; j++) {
  10. if (strs[0].charAt(index) != strs[j].charAt(index)) {
  11. return false;
  12. }
  13. }
  14. return true;
  15. }
  16. for (let i in start) {
  17. if (!vaild(i)) break;
  18. result.push(start.charAt(i));
  19. }
  20. return result.join('');
  21. };

Runtime: 60 ms, faster than 52.23% of JavaScript online submissions for Longest Common Prefix.