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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/43520.html
標籤:其他
