p14

LeetCode p14 Longest Common Prefix 题解

1.题目:

Write a function to find the longest common prefix string amongst an array of strings.

题意:

输入一个字符数组,找出他们最长的共同前缀字符串。

2.解题思路:

见代码
strs[i].indexOf(s) //查找字符或者子串第一次出现的地方

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length < 1)
return "";
String s = strs[0];

for (int i = 1; i < strs.length; i++) {
if (s.equals(""))
break;
while (strs[i].indexOf(s) != 0) {
s = (String) s.subSequence(0, s.length() - 1);

}

}
return s;
}
}

4.一些总结: