Advertisement
Guest User

asd

a guest
Aug 14th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | None | 0 0
  1. public class Solution {
  2.     public int LengthOfLongestSubstring(string s) {
  3.        
  4.         Dictionary<char,int> charToPositionMap = new Dictionary<char,int>();
  5.         int currentStart = 0;
  6.         int longestSubstringLength = 0;
  7.         int currentSubstringLength = 0;
  8.        
  9.         while(currentStart < s.Length)
  10.         {
  11.             bool duplicated = false;
  12.             for(int i = currentStart; i < s.Length; i++)
  13.             {
  14.                 if(!charToPositionMap.ContainsKey(s[i]))
  15.                 {
  16.                     charToPositionMap.Add(s[i],i);
  17.                     currentSubstringLength++;
  18.                 }
  19.                 else
  20.                 {
  21.                    if(currentSubstringLength > longestSubstringLength) longestSubstringLength = currentSubstringLength;
  22.                     currentStart = charToPositionMap[s[i]] + 1;
  23.                     charToPositionMap.Clear();
  24.                     currentSubstringLength = 0;
  25.                     duplicated = true;
  26.                     break;
  27.                 }
  28.             }
  29.             if (currentSubstringLength > longestSubstringLength) longestSubstringLength = currentSubstringLength;
  30.              if(!duplicated) currentStart = s.Length;
  31.         }
  32.         return longestSubstringLength;
  33.  
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement