Suppose there is a string "ABCDEBFGH"
then the longest non-repeating string is "CDEBFGH" , Length is 7
if: Abcdbefbghijij
Should output:befbghij
|
Take the string abcbef as an example Use a data structure POS to record the subscript that has occurred for each element, starting with-1 Starting from s[0], pos[' a '] = = 1, indicating that a has not appeared, so that pos[' a '] = 0, as a "join the current string", while the length + + Similarly pos[' B '] = 1,pos[' c '] = 2 To S[3], pos[' B ']! =-1, stating that ' B ' has already appeared in the front, at this point can get a non-repeating string "abc", refresh the current maximum length, and then do the following processing: POS[S[0~2]] =-1, that is, "AB" "moves out of the current string", while the current length minus 3
Repeat the above process |
|
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace consoleapplication10{class Program {static void Main (string[] args) {string ss = "Abcdbefbghijij"; var list = ss. ToCharArray (); int left = 0; int right = 0; Getlen (list, out left, off right); Console.WriteLine (ss. Substring (left, Right-left + 1)); }//<summary>///</summary>/<param name= "list" ></param> <param name= ' left ' >right index from 0</param>//<param name= ' right ' >right index from 0 </param>//<returns></returns> public static int Getlen (char[) list, out int left, out I NT right) {if (list = = NULL | | list. Length <= 0) {throw new Exception ("The input list length is 0"); } int len = list. Length; left = 0; right = 0; int maxlen = 0; int start = 0; int tempmaxlen = 0; Dictionary<char, int> cache = new Dictionary<char, int> (); for (int i = 0; i < len; i++) {if (!cache). Keys.contains (List[i]) | | CACHE[LIST[I]]==-1)//This build does not exist or is built, but the value is-1, indicating that the character has not yet appeared. {tempmaxlen++; Cache. ADD (List[i], i); } else {//there is duplicated char abcdbefgh if (Tempmaxlen > MaxLen) {maxlen = Tempmaxlen; left = start; right = I-1; } Tempmaxlen = I-cache[list[i]]; for (int j = start; J < Cache[list[i]]; j++)//Note: There are many examples on the web that are clear about everything in this cache and should be wrong; only the characters in front of the last repeating character should be known. {Cache[list[j]] =-1; } start = Cache[list[i]] + 1; Cache[list[i]] = i; }} if (Tempmaxlen > MaxLen) {maxlen = Tempmaxlen; left = start; right = len-1; } return maxlen; } }}
There are some examples on the Internet, so I have re-wrote the longest non-repeating string