【最长公共前缀】算法优化笔记
生活随笔
收集整理的這篇文章主要介紹了
【最长公共前缀】算法优化笔记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:編寫一個函數來查找字符串數組中的最長公共前綴。如果不存在公共前綴,返回空字符串 “”。
示例 1:輸入: ["flower","flow","flight"]輸出: "fl"示例 2:輸入: ["dog","racecar","car"]輸出: ""解釋: 輸入不存在公共前綴。來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/longest-common-prefix
初步分析
詳細代碼
縮減法
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);}}return strpublic;} }個人暴力法
public class Solution {public string LongestCommonPrefix(string[] strs) {if (strs.Length <= 0) return "";string sum="";for (int i = 0; i < strs[0].Length; i++){if (IsIndexEqual(strs, i) == "")return sum;elsesum += IsIndexEqual(strs, i);}return sum;}public string IsIndexEqual(string[] strs,int index) {for (int i = 0; i < strs.Length; i++){if (index >= strs[i].Length)return "";}char before = strs[0][index];int isit=1;for (int i = 0; i < strs.Length; i++){if (before == strs[i][index])isit &= 1;elseisit &= 0;}if (isit == 1)return before.ToString();elsereturn "";} }總結
以上是生活随笔為你收集整理的【最长公共前缀】算法优化笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【罗马数字转整数】算法优化笔记
- 下一篇: 【SDK接入篇】【1】Unity的int