比如: 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。