Programming/LeetCode

[Leetcode] #14. Longest Common Prefix (repeat : 0 )

dev.pudding 2024. 1. 31. 15:30
728x90

Description 

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.


Solution 

class Solution{
	public String longestCommonFix(String[] strs){
    	
        if(strs == null || strs.length == 0) return "";
        
        String prefix = strs[0];
        
        for(String s : strs)
        	while(s.indexOf(prefix) != 0) 
            	prefix = prefix.substring(0,prefix.length()-1);
    
    	return prefix;
    }

}

prefix = prefix.substring(0,prefix.length()-1) indicates that string is substracted till it reachs till s.indexOf(prefix) == 0 

Time complexity O(n) as it iterates through the array  

Space Complexity O(1)