Algorithms—14.Longest Common Prefix

原创 2015年07月07日 14:29:38

思路:先比较前2个String,找出公共开头,然后从第三个开始逐次比较,当公共开头字符串长度为0时,直接返回"";

public class Solution {
    public String longestCommonPrefix(String[] strs) {
    	if (strs.length==0) {
			return "";
		}
        if (strs.length==1) {
			return strs[0];
		}
        int n=0;
        if (strs[0].length()<strs[1].length()) {
			n=strs[0].length();
		}else {
			n=strs[1].length();
		}
        String answer="";
        for (int i = 0; i < n; i++) {
        	String k0=strs[0].substring(i,i+1);
        	String k1=strs[1].substring(i,i+1);
        	if (k0.equals(k1)) {
				answer+=k0;
			}else {
				break;
			}
		}
        if (strs.length==2) {
			return answer;
		}
        for (int i = 2; i < strs.length; i++) {
        	if (answer.length()==0) {
				return "";
			}
			int length=0;
			String k="";
			if (strs[i].length()<answer.length()) {
				length=strs[i].length();
			}else {
				length=answer.length();
			}
			while (!answer.substring(0, length).equals(strs[i].substring(0, length))) {
				length--;
			}
			answer=answer.substring(0,length);
		}
        return answer;
    
        
    }
}


耗时:320ms,处于中游,一次编译通过,哇哈哈。


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 14 — Longest Common Prefix(C++ Java Python)

题目:http://oj.leetcode.com/problems/longest-common-prefix/ Write a function to find the longest commo...

14. Longest Common Prefix

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

LeetCode OJ-14.Longest Common Prefix

LeetCode OJ-14.Longest Common Prefix题目描述 Write a function to find the longest common prefix string...

LeetCode 14 Longest Common Prefix(最长公共前缀)(String)

翻译写一个函数(或方法)来寻找一个字符串数组中的最长公共前缀。原文Write a function to find the longest common prefix string amongst a...
  • NoMasp
  • NoMasp
  • 2015-10-16 22:05
  • 5193

LeetCode #14 Longest Common Prefix 最长公共前缀 解题小节

1 题目理解题目的理解就是给定一堆字符串,从中找出最长的公共前缀。前缀是什么?可以理解为一个字符串开头的几个字母,那么公共前缀,就是这一堆字符串开头的前几个(前缀)的最大相同长度是多少。。。就是所有字...

Leetcode_14_Longest Common Prefix

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/40555783 Longest Common Prefix ...

LeetCode之14---Longest Common Prefix

题目:   Write a function to find the longest common prefix string amongst an array of strings. 题目大意:  ...

Leetcode-14. Longest Common Prefix

Problem Description: Write a function to find the longest common prefix string amongst an array of ...

14. Longest Common Prefix [easy] (Python)

题目链接https://leetcode.com/problems/longest-common-prefix/题目原文 Write a function to find the longest ...

LeetCode12~14 Integer to Roman/Roman to Integer/Longest Common Prefix

一:Integer to Roman 题目: Given an integer, convert it to a roman numeral. Input is guaranteed t...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)