[leetcode] Longest Common Prefix

回眸只為那壹抹淺笑 提交于 2021-02-13 06:14:23

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

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

思路1:以第一个字符串为基准,依次比较后面字符串每一位的情况,如有不相同或者有字符串提前结束即返回。


public class Solution {
	public String longestCommonPrefix(String[] strs) {
		int n = strs.length;
		if(n<1)
			return "";
		int len0 = strs[0].length();
		int i, j;
		outer: for (i = 0; i < len0; i++) {
			char cur = strs[0].charAt(i);
			for (j = 1; j < n; j++) {
				if (i >= strs[j].length() || strs[j].charAt(i) != cur) {
					break outer;
				}

			}
		}
		return strs[0].substring(0, i);

	}

	public static void main(String[] args) {
		System.out.println(new Solution().longestCommonPrefix(new String[] {
				"abbasda", "abb", "abbc" }));
		System.out.println(new Solution().longestCommonPrefix(new String[] {
				"", "ab", "ac" }));
		System.out.println(new Solution()
				.longestCommonPrefix(new String[] { "abc" }));
		System.out.println(new Solution()
		.longestCommonPrefix(new String[] {}));

	}
}






易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!