Easy understand Java solution with comments


  • 1
    W
    // 思路: 以第一个字符串为基准,依次比较各个字符
    public String longestCommonPrefix(String[] strs) {
    	if (strs == null || strs.length == 0)
    		return "";
    	String str = strs[0]; // 以第一个字符串为基准
    	int index = 0; // 当前正在比较的下标
    	while (index < str.length()) {
    		// 依次取后面字符串与基准字符串比较
    		for (int i = 1; i < strs.length; i++) {
    			String cur = strs[i];
    			// 注意下标不要越界
    			if (index < str.length() && index < cur.length()) {
    				if (str.charAt(index) != strs[i].charAt(index)) {
    					return str.substring(0, index);
    				}
    			} else {
    				return str.substring(0, index);
    			}
    		}
    		index++;
    	}
    	return str; // 基准字符串最短
    }
        // 时间复杂度: O(M*N)

  • 0
    A

    English Please!


Log in to reply
 

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