Java accepted solution for Longest Common Prefix for reference


  • 0
    B
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs.length == 0)
    			return "";
    			
            int[] lengthArr = new int[strs.length];
    
    		for (int i = 0; i < strs.length; i++) {
    			lengthArr[i] = strs[i].length();
    		}
    		Arrays.sort(lengthArr);
    		int shortest = lengthArr[0];
    
    		int commonLength = 0;
    		for (int i = 0; i < shortest; i ++) {
    			List<String> list = new ArrayList<>();
    
    			for (int j = 0; j < strs.length; j++) {
    				list.add(String.valueOf(strs[j].charAt(i)));
    			}
    
    			if (!isAllSameValue(list)) {
    				commonLength = i;
    				break;
    			}
    
    			commonLength = i + 1;
    		}
    
    		return strs[0].substring(0, commonLength);
        }
        
        private boolean isAllSameValue(List<String> strs)
    	{
    		String tmp = strs.get(0);
    
    		for (String s : strs) {
    			if (!s.equals(tmp))
    				return false;
    		}
    
    		return true;
    	}
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.