LeetCode, leetcodeoj
Description:
Given a string, find the length of the longest substring without repeating characters. for example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. for "bbbbb" the longest substring is "B", with the length of 1.
It is to find the longest string without repeated characters from a string.
Ideas:
Traverse the string and use a hash table to save each character one by one: [character, location]. If there is a duplicate:
1. Update the maximum length of the current position
2. Continue to traverse from the next character at the last occurrence of the Current Character
3. Clear the hash table
Later, it was found that the operation performance of clearing the hash table was too high to pass the test data.
Use a Boolean array keys to replace the hash function (each bit is initialized to false), and use the start variable to replace the position of the last repeated character (initialized to 0 ):
1. use an array with a length of 256. For each character in string s, traverse one by one to determine whether the current s [I] has already appeared in keys [s [I]. If not:
Keys [s [I] is set to true
If:
1. Compare the distance from I to start with the current maximum length.
2. Reset keys [start, I] to false and continue from s [start + 1 ].
Implementation Code:
public class Solution { public int LengthOfLongestSubstring(string s) { if(string.IsNullOrWhiteSpace(s)){return 0; } var keys = new bool[256]; int max = 0; int start = 0; for (int i = 0; i < s.Length; i++) { var current = s[i]; if (keys[current]) { max = Math.Max(max, i - start); for (int k = start; k < i; k++) { if (s[k] == current) { start = k + 1; break; } keys[s[k]] = false; } } else { keys[current] = true; } } max = Math.Max(s.Length - start, max); return max; }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.