Saturday, August 19, 2017

LeetCode - 14. Longest Common Prefix

Source Link:
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)
}
 

1 comment:

  1. I found that solution very popular and helpful:
    https://www.youtube.com/watch?v=ehRud05f-F0&ab_channel=EricProgramming

    ReplyDelete

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...