0014. Longest Common Prefix (E)
Longest Common Prefix (E)
题目
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
题意
找到给定字符串组的公共前缀。
思路
以第一个字符串中的字符为基准,再去比对其余字符串中对应位置处的字符。
代码实现
Java
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String ans = "";
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 ans;
}
}
ans += c;
}
return ans;
}
}
JavaScript
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
if (strs.length === 0) {
return ''
}
let prefix = ''
for (let i = 0; i < strs[0].length; i++) {
let c = strs[0][i]
for (let j = 1; j < strs.length; j++) {
if (i === strs[j].length || strs[j][i] !== c) {
return prefix
}
}
prefix += c
}
return prefix
}