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)
}
}
Subscribe to:
Post Comments (Atom)
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 ...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ Question: An integer M and a...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ Question: A zero-indexed array A consi...
-
Source Link: https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ Question: A non-empty zero-indexed array A...
I found that solution very popular and helpful:
ReplyDeletehttps://www.youtube.com/watch?v=ehRud05f-F0&ab_channel=EricProgramming