Longest Common Prefix - Leetcode 14 - Java

preview_player
Показать описание
Longest Common Prefix - Leetcode 14 - Java

--------------------------------ABOUT--------------------------------
🧑🏻 My name is David and I am a software engineer at Meta. My passion is teaching software devs how to pass the grueling technical interviews to help them land their 6-figure dream tech job.

I have received 3 six-figure offers from Google, Meta, and Amazon.

🔬I provide content that will allow you to understand the thought process, pseudocode, time complexity, and code when approaching coding problems.

--------------------------------SOCIAL--------------------------------

💬 If you have any topic or questions you want me to cover, let me know in the comment section below ~ ฅʕ•ᴥ•`ʔ ฅʕ•ᴥ•`ʔ ฅʕ•ᴥ•`ʔ

#technicalinterview #techcareer #softwareengineer
Рекомендации по теме
Комментарии
Автор

I wonder if it would just be easier to sort the array and then go with while loop increasing the integer c as long as the index at the letter at index c of first and last words are the same. Once they are different, we break out of the loop and return substring. Example:

public String longestCommonPrefix(String[] strs) {

if (strs.length == 0){
return "";
}

Arrays.sort(strs);

String first = strs[0];
String last = strs[strs.length - 1];

int c = 0;
while(c < first.length()){
if(first.charAt(c) != last.charAt(c)){
break;
}
c++;
}
return last.substring(0, c);
}

ladro_magro
Автор

easy to understand thanks .can u zoom in the screen

praveenguduru
Автор

Runtime 1ms, memory beats 60%
class Solution {

public String longestCommonPrefix(String[] strs) {
//edge case, if there's only one string in the array, return that string
if (strs.length == 1) return strs[0];
//loop through all strings, find the shortest string
String minStr = strs[0];
for (String x : strs) {
if (x.length() < minStr.length()) {
minStr = x;
}
}
//edge case, if the shortest string was just blank, return ""
if (minStr.length() == 0) return "";
//loop through each charAt location in each string
for (int i = 0; i < minStr.length(); i++) {
//test char is the charAt index i in the first string
char test = strs[0].charAt(i);
//check the rest of the strings to see if they have the same char
//if there is a mismatch, return the substring up to that point
//if no mismatch, then the outer loop increments and the substring gets longer
for (String y : strs) {
if (y.charAt(i) != test) return minStr.substring(0, i);
}
}
//if the loop survives, then the entire minStr is the shortest. Return it.
return minStr;
}
}

BBand
Автор

my brother in christ get a quiet keyboard, its so distracting, other than that thank you

Cangrejozurdo