Leetcode14. Longest Common Prefix
Posted 于淼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode14. Longest Common Prefix相关的知识,希望对你有一定的参考价值。
Question:
Write a function to find the longest common prefix string amongst an array of strings.
LeetCode submission:
public class Solution { public String longestCommonPrefix(String[] strs) { String ans = ""; if (strs.length == 0 || strs == null) { return ""; } if(strs.length==1) ans=strs[0]; String min = strs[0]; for (int i = 1; i < strs.length; i++) {// strs数组中字符串的个数 //System.out.println(strs.length); while (strs[i].indexOf(min) != 0) { min = min.substring(0, min.length() - 1); } ans=min; } System.out.println(ans); return ans; } }
Executable code:
public class L14 { public String longestCommonPrefix(String[] strs) { String ans = ""; if (strs.length == 0 || strs == null) { return ""; } if(strs.length==1) ans=strs[0]; String min = strs[0]; for (int i = 1; i < strs.length; i++) {// strs数组中字符串的个数 //System.out.println(strs.length); while (strs[i].indexOf(min) != 0) { //当strs[]与min无法匹配时将min字符串长度减一 min = min.substring(0, min.length() - 1); } ans=min; } System.out.println(ans); return ans; } public static void main(String[] args) { L14 l14 = new L14(); String[] strs = {"a","a","b"}; l14.longestCommonPrefix(strs); } }
Note:
strs[i].indexOf(min)//返回min的第一个字符在strs[i]中的第一个位置,
min = min.substring(0, min.length() - 1);////当strs[]与min无法匹配时将min字符串长度减一
以上是关于Leetcode14. Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章
leetcode14. longest common prefix
Leetcode 14. Longest Common Prefix
Leetcode 14 Longest Common Prefix
Leetcode14. Longest Common Prefix