首页 > 编程语言 > 详细

LeetCode -- 求字符串数组中的最长公共前缀

时间:2015-07-25 15:14:13      阅读:279      评论:0      收藏:0      [点我收藏+]

题目描述:


Write a function to find the longest common prefix string amongst an array of strings.
就是给定1个字符串数组,找出公共最长前缀。


思路很直接,使用1个索引来存最长公共前缀的长度就可以了。


注意, 如果使用1个字符串变量来存前缀的话,是不能AC的,因为题目不允许使用额外的空间。



public string LongestCommonPrefix(string[] strs) {
        
    if(strs == null || strs.Length == 0){
	    return string.Empty;
	}
	
	if(strs.Length == 1){
	    return strs[0];
	}
	
	var index = 0;
	for(var j = 0;j < strs[0].Length; j++){
		for(var i = 1;i < strs.Length; i++){
			if(j >= strs[i].Length || strs[0][j] != strs[i][j]){
				return strs[0].Substring(0,index);
			}
		}
		index++;
		
	}
	
	return strs[0].Substring(0 ,index);
	
    }


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

LeetCode -- 求字符串数组中的最长公共前缀

原文:http://blog.csdn.net/lan_liang/article/details/47056413

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!