我現(xiàn)在在做一個叫《leetbook》的開源書項目巢价,把解題思路都同步更新到github上了恶迈,需要的同學(xué)可以去看看
地址:https://github.com/hk029/leetcode
這個是書的地址:https://hk029.gitbooks.io/leetbook/
014.Longest Common Prefix[E]
問題
Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
思路
這個沒啥思路的凰棉,怎么都要兩重循環(huán)醋火,因為是最長公共子串奄薇,隨便找一個(一般是第一個作為基準)碟联,然后拿拿的首部慢慢去匹配后面的字符串就行了。
public class Solution {
public String longestCommonPrefix(String[] strs) {
String s = "";
if(strs.length == 0)
return "";
for(int i = 0; i < strs[0].length();i++)
{
char c = strs[0].charAt(i);
for(int j = 1;j < strs.length;j++)
{
if(i >= strs[j].length() || strs[j].charAt(i) != c)
return s;
}
s += c;
}
return s;
}
}