https://leetcode.com/problems/longest-common-prefix/description/
Question:
Write a function to find the longest common prefix string amongst an array of strings.
Hint:
https://leetcode.com/problems/longest-common-prefix/solution/
My Solution: Note:
1. we will shorten the common prefix if not perfectly match
2. Using Horizontal Scanning: from the 1st string to the last string
for(int i=1; i< strs.length; i++)
3. match: using string.indexOf(string)==0
while( prefix_match == false){
if(strs[i].indexOf(prefix) ==0) {
prefix_match = true;
}
else{
prefix = prefix.substring(0, prefix.length()-1);
//shorten prefix: using string.substring(0, length-1)
}
}
I found that solution very popular and helpful:
ReplyDeletehttps://www.youtube.com/watch?v=ehRud05f-F0&ab_channel=EricProgramming