Longest Common Prefix

https://leetcode.com/problems/longest-common-prefix/

Write a function to find the longest common prefix string amongst an array of strings.

 

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
        	return "";
        }
        int i = 0;
        StringBuilder sb = new StringBuilder();
        while (true) {
        	char ch = 0;
        	for (String s : strs) {
        		if (i == s.length()) {
        			return sb.toString();
        		}
        		if (ch == 0) {
        			ch = s.charAt(i);
        		}
        		if (ch != s.charAt(i)) {
        			return sb.toString();
        		}
        	}
        	sb.append(ch);
        	i++;
        }
    }
}

 

你可能感兴趣的:(long)