首页 > 编程语言 > 详细

14. 字符串数组的最长公共前缀 Longest Common Prefix

时间:2017-04-16 00:19:36      阅读:287      评论:0      收藏:0      [点我收藏+]
Write a function to find the longest common prefix string amongst an array of strings.
  1. public class Solution {
  2. public string LongestCommonPrefix(string[] strs) {
  3. StringBuilder result = new StringBuilder();
  4. if (strs != null && strs.Length > 0) {
  5. Array.Sort(strs);
  6. char[] a = strs[0].ToCharArray();
  7. char[] b = strs[strs.Length - 1].ToCharArray();
  8. for (int i = 0; i < a.Length; i++) {
  9. if (b.Length > i && b[i] == a[i]) {
  10. result.Append(b[i]);
  11. } else {
  12. return result.ToString();
  13. }
  14. }
  15. return result.ToString();
  16. } else {
  17. return "";
  18. }
  19. }
  20. }







14. 字符串数组的最长公共前缀 Longest Common Prefix

原文:http://www.cnblogs.com/xiejunzhao/p/bca1d564401e3306dc16499cd8ffd10b.html

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