Iterative solution in Java


  • 0
    M

    Simple iterative solution.

    public class Solution {
        public String longestCommonPrefix(String[] words) {
            if (words == null) {
                return null;
            } else if (words.length == 0) {
                return "";
            } else if (words.length == 1) {
                return words[0];
            }
            
            String currentWord = words[0];
            
            for (int i = 1; i < words.length; i++) {
                int j = 0;
                int limit = Math.min(words[i].length(), currentWord.length());
                while (j < limit) {
                    if (words[i].charAt(j) != currentWord.charAt(j)) {
                        break;
                    }
                    j++;
                }
                currentWord = currentWord.substring(0, j);
            }
            
            return currentWord;
        }
    }
    

Log in to reply
 

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