Problem: 找出给定的string数组中最长公共前缀
 
由于是找前缀,因此调用indexOf函数应当返回0(如果该字符子串为字符串的前缀时),如果不是则返回-1
Return:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
 
参考代码:
package leetcode_50;

/***
 * 
 * @author pengfei_zheng
 * 最长公共前缀
 */
public class Solution14 {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0)    return "";//字符串数组为空或者长度为0
        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;//返回前缀
    }
}

 

相关文章:

  • 2021-06-12
  • 2021-12-22
  • 2021-06-16
  • 2021-10-02
  • 2022-12-23
  • 2021-12-14
  • 2022-01-15
猜你喜欢
  • 2021-05-06
  • 2022-01-26
  • 2021-07-09
  • 2021-12-23
  • 2021-09-14
  • 2021-04-19
  • 2021-06-28
相关资源
相似解决方案