给定一个字符串数组,我们必须找到它们之间最长的公共前缀。如果没有前缀,则返回空字符串。
输入: ["flower","flow","flight"] 得到的目标值: "fl" 输入: ["dog","racecar","car"] 得到的目标值: "" There is no common prefix among the input strings.
这个想法是去的。
- const longestCommonPrefix = (strs) => {
- //If empty array return empty string
- if(strs.length === 0){
- return "";
- }
-
- //To track the prefix
- let lc = "";
-
- //Sort the string in ascending order
- strs.sort((a, b) => ('' + a).localeCompare(b));
-
- //Get the smallest string.
- let smallest = strs[0];
-
- //so that we have to iterate for it only.
- for(let i = 0; i < smallest.length; i++){
- //Get the first letter
- let current = smallest[i];
-
- //Flag to check if prefix is present in the remaining string
- let isPresent = true;
-
- for(let values of strs){
- //Break if different letter
- if(values[i] !== current){
- isPresent = false;
- break;
- }
- }
-
- //Break the loop if no prefix
- if(i === 0 && !isPresent){
- break;
- }
-
- //Add the prefix
- lc += isPresent ? current : '';
- }
-
- //return the prefix
- return lc;
- };
-
- console.log(longestCommonPrefix(["flower","flow","flight"]));// 结果"f1"
-
-
时间复杂度:O(nlogn +(n *字符串中最小单词的长度))。
空间复杂度:O(1)或O(n),如果我们使用不同的排序。
从概念上讲,这就是它的工作原理。
- const longestCommonPrefix = (strs) => {
- //If empty array
- if(strs.length == 0) {
- return "";
- }
-
- //Get the first word
- let str = strs[0];
-
- //look for prefix in each word
- for (const word of strs) {
- while (word.indexOf(str) !== 0) {
- // remove one character from the end
- str = str.substring(0, str.length - 1);
- if (str === ""){
- break;
- }
- }
- }
- return str;
- };
时间复杂度:O(n * 最大字符串的长度)。
空间复杂度:O(1)。