【最长公共前缀】算法优化笔记
题目:编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-common-prefix 初步分析 暴力循环嵌套比较得出最长前缀 取第一个string为原值,逐步比较缩短得到最长公共前缀。 详细代码 缩减法 public class Solution { public string LongestCommonPrefix ( string [ ] strs ) { if ( strs . Length == 0 ) return "" ; string strpublic = strs [ 0 ] ; for ( int i = 0 ; i < strs . Length ; i ++ ) { while ( strs [ i ] . IndexOf ( strpublic ) != 0 ) { strpublic = strpublic . Substring ( 0 , strpublic . Length - 1 ) ; }