Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
"abcabcbb"
, the answer is "abc"
, which the length is 3.
Given
"bbbbb"
, the answer is "b"
, with the length of 1.
Given
"pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequenceand not a substring.Solution in C
int is_present (char ch, char *sol, int front, int rear, int size) {
int i;
if (front == 0 && rear == -1)
return -2;
for (i = rear; (i != front); i = (i + 1) % size) {
if (sol[i] == ch)
return i;
}
/*
if (rear == front - 1) {
if (sol[i] == ch)
return i;
}*/
return -1;
}
int lengthOfLongestSubstring(char* s) {
char *sol;
int len, front = 0, rear = -1, i = 0;
int curr_len = 0, max_len = 0, size, op;
len = strlen(s);
if (len == 0)
return 0;
size = len + 1;
sol = (char *)malloc(sizeof(char) * size);
if (sol == NULL)
return 0;
while (i < len) {
op = is_present(s[i], sol, front, rear, size);
switch (op) {
case -2:
sol[front] = s[i];
front++;
rear = 0;
curr_len = front - rear;
max_len = curr_len;
break;
case -1:
sol[front] = s[i];
front = (front + 1) % size;
curr_len++;
if (max_len < curr_len)
max_len = curr_len;
break;
default:
sol[front] = s[i];
rear = (op + 1) % size;
/*if (rear == front)
rear = front;
*/
front = (front + 1) % size;
if (front >= rear) {
curr_len = front - rear;
} else {
curr_len = (size - rear) + front;
}
if (max_len < curr_len)
max_len = curr_len;
break;
}
i++;
}
free(sol);
return max_len;
}
Solution in Python:
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_len = 0
i = 0
while i < len(s):
dic = {}
dic[s[i]] = 1
j = i + 1
count = 1
while j < len(s):
if s[j] in dic:
break
count = count + 1
dic[s[j]] = 1
j = j + 1
if count > max_len:
max_len = count
i = i + 1
return max_len