Share my accepted Java solution!


  • 0
    I
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return new String("");
            } else if (strs.length == 1) {
                return strs[0];
            }
            int pos;
            char now;
            boolean success = false;
            for (pos = 0;;pos++) {
                if (strs[0].length() <= pos) {
                    break;
                }
                now = strs[0].charAt(pos);
                for (int i = 1; i < strs.length; ++i) {
                    if (pos >= strs[i].length() || strs[i].charAt(pos) != now) {
                        success = true;
                        break;
                    }
                }
                if (success) break;
            }
            return strs[0].substring(0, pos);
        }
    }

Log in to reply
 

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