编写一个函数来查找字符串数组中的最长公共前缀。
    如果不存在公共前缀,返回空字符串 “”。

    示例 1:

    输入: [“flower”,”flow”,”flight”] 输出: “fl”

    示例 2:

    输入: [“dog”,”racecar”,”car”] 输出: “” 解释: 输入不存在公共前缀。

    说明:
    所有输入只包含小写字母 a-z 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-common-prefix


    1. class Solution {
    2. public String longestCommonPrefix(String[] strs) {
    3. if (strs.length == 0){
    4. return "";
    5. }
    6. StringBuilder common = new StringBuilder();
    7. String result = strs[0];
    8. for (int i = 1; i < strs.length; i++) {
    9. int len1 = result.length();
    10. int len2 = strs[i].length();
    11. for (int j = 0; j <= len2; j++) {
    12. if (j < len2 && j < len1 && strs[i].charAt(j) == result.charAt(j)){
    13. common.append(strs[i].charAt(j));
    14. }else {
    15. result = String.valueOf(common);
    16. common.delete(0,j);
    17. break;
    18. }
    19. }
    20. }
    21. return result;
    22. }
    23. }