您的位置:首页

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

2017-05-28 17:56 591 查看
题目描写叙述:

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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: