Java Solution using label


  • 2
    K
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs == null || strs.length == 0) return "";
            int i;
        Label1: for(i = 0; i < strs[0].length(); i++){
                char start = strs[0].charAt(i);
                for(String x : strs){
                    if(i < x.length() && x.charAt(i) == start) continue;
                    else break Label1;
                }            
            }
            return strs[0].substring(0,i);
        }
    }
    
    idea is to use the first string element as the criteria.
    use parameter i as index
    if all the strings have the same character at index i, i++, otherwise exit the outer loop
    now the value of parameter i is the length of the prefix
    extract the substring from the first string element and return

Log in to reply
 

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