您好,登錄后才能下訂單哦!
比如: ababcdebc,那他最大的子字符串就是:abcde
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { string s = "abcababcdefgfg"; char[] list = s.ToCharArray(); FindMaxSubDifferenceString ss = new FindMaxSubDifferenceString(); ss.FindMaxSubDifferenceStringS(list, s.Length); string s1 = "aaaaaa"; char[] list1 = s1.ToCharArray(); ss.FindMaxSubDifferenceStringS(list1, s1.Length); string s2 = "ababab"; char[] list2 = s2.ToCharArray(); ss.FindMaxSubDifferenceStringS(list2, s2.Length); string s3 = "abcababcdefgfgabcababcdefgfg"; char[] list3 = s3.ToCharArray(); ss.FindMaxSubDifferenceStringS(list3, s3.Length); } } public class FindMaxSubDifferenceString { public bool IsDup(char[] list, int len, char targetChar, int begin, int end, out int targetIndex) { targetIndex = -1; // Note: first, we need to check all parameters are valid, such as list is null, len >0, or begin <end, begin>0, end<len, etc for(int i=begin;i<=end; i++) { if(list[i]==targetChar) { targetIndex = i; return true; } } return false; } public void FindMaxSubDifferenceStringS(char[] list, int len) { if (list == null) return; if (len <= 0) return; int maxSubStringLen = 0; int maxSubStringBeginIndex = 0; int currentMaxSubStringBeginIndex = 0; int currentMaxSubLen = 0; for (int i = 1; i < len; i++) { int dupIndex = -1; if (IsDup(list, len, list[i], currentMaxSubStringBeginIndex, i - 1, out dupIndex)) { currentMaxSubLen = i - currentMaxSubStringBeginIndex; if (currentMaxSubLen > maxSubStringLen) { maxSubStringLen = currentMaxSubLen; maxSubStringBeginIndex = currentMaxSubStringBeginIndex; } else { } currentMaxSubStringBeginIndex = dupIndex + 1; } else //not dup { } } if (maxSubStringLen == 0) { maxSubStringLen = len; } Console.Write("Input string: "); for (int i = 0; i < len; i++) { Console.Write(list[i]); } Console.WriteLine(""); Console.Write("After Input: "); for (int i = maxSubStringBeginIndex; i < maxSubStringBeginIndex + maxSubStringLen; i++) { Console.Write(list[i]); } Console.WriteLine(""); } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。