0%

leetcode 14 Solution

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.demo.s14;

/**
* 最长公共前缀
* 编写一个函数来查找字符串数组中的最长公共前缀。
*
* 如果不存在公共前缀,返回空字符串 ""。
*/
public class Solution {
public String longestCommonPrefix(String[] strs) {
//特殊情况判断
if (strs == null || strs.length == 0) {
return "";
}
//取第一个数组做对比
int length = strs[0].length();
//字符串个数
int count = strs.length;
//遍历字符串字符
for (int i = 0; i < length; i++) {
char c = strs[0].charAt(i);
//对比其他字符串
for (int j = 1; j < count; j++) {
//达到其他字符串最大长度 或者 字符匹配不上,则终止
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return strs[0].substring(0, i);
}
}
}
return strs[0];

}
}