14. 最长公共前缀
一、Java
class Solution {public String longestCommonPrefix(String[] strs) {for (int l = 0; ; l++) {for (int i = 0; i < strs.length; i++) {if (l >= strs[i].length() || strs[i].charAt(l) != strs[0].charAt(l)) return strs[0].substring(0, l);}}}
}
二、C++
#include <string>
#include <vector>using namespace std;class Solution {
public:string longestCommonPrefix(vector<string> &strs) {for (int l = 0;; l++) {for (int i = 0; i < strs.size(); i++) {if (l >= strs[i].length() || strs[i][l] != strs[0][l]) return strs[0].substr(0, l);}}}
};
三、Python
from typing import Listclass Solution:def longestCommonPrefix(self, strs: List[str]) -> str:l = 0while True:for i in range(len(strs)):if l >= len(strs[i]) or strs[i][l] != strs[0][l]:return strs[0][0:l]l += 1
四、JavaScript
var longestCommonPrefix = function (strs) {for (let l = 0; ; l++) {for (let i = 0; i < strs.length; i++) {if (l >= strs[i].length || strs[i][l] != strs[0][l]) return strs[0].substring(0, l);}}
};
五、Go
package mainfunc longestCommonPrefix(strs []string) string {for l := 0; ; l++ {for i := 0; i < len(strs); i++ {if l >= len(strs[i]) || strs[i][l] != strs[0][l] {return strs[0][0:l]}}}
}