zoukankan      html  css  js  c++  java
  • 14. Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings.
    写一个函数
    在字符串数组中找到最长公共子字符串
    高票答案,利用了indexof查找子字符串功能~
    public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; String pre = strs[0]; int i = 1; while(i < strs.length){ while(strs[i].indexOf(pre) != 0) pre = pre.substring(0,pre.length()-1); i++; } return pre; }

    我的答案从头开始,一个字符一个字符地找~

    class Solution {
    public String longestCommonPrefix(String[] strs) {
    StringBuffer result = new StringBuffer("");
    if (strs.length==0)
    return result.toString();
    for (int i = 0; i < strs[0].length(); i++) {
    char thechar = strs[0].charAt(i);
    for (int j = 1; j < strs.length; j++) {
    if (strs[j].length() <= i)
    return result.toString();
    if (strs[j].charAt(i) != thechar)
    return result.toString();
    }
    result.append(thechar);
    }
    return result.toString();
    }
    }

     
  • 相关阅读:
    [CF598E] Chocolate Bar
    [CF629D] Babaei and Birthday Cake
    [CF961D] Pair Of Lines
    [CF468B] Two Sets
    [CF767C] Garland
    [CF864E] Fire
    [CF578C] Weakness and Poorness
    [CF555B] Case of Fugitive
    [CF118E] Bertown roads
    [CF1301D] Time to Run
  • 原文地址:https://www.cnblogs.com/mafang/p/8554392.html
Copyright © 2011-2022 走看看