Problem 3: longest substring
This commit is contained in:
parent
e1dedc1464
commit
b63e4594d9
4 changed files with 90 additions and 0 deletions
1
problems/3-longest-substring/Makefile
Symbolic link
1
problems/3-longest-substring/Makefile
Symbolic link
|
@ -0,0 +1 @@
|
|||
../template/Makefile
|
59
problems/3-longest-substring/lib.c
Normal file
59
problems/3-longest-substring/lib.c
Normal file
|
@ -0,0 +1,59 @@
|
|||
#include <string.h>
|
||||
#include "lib.h"
|
||||
|
||||
void resetArray(int* count) {
|
||||
int length = '~' - 32 + 1;
|
||||
for (int i=0; i<length; i++) {
|
||||
count[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
int lengthOfLongestSubstring(char * s) {
|
||||
// Create an array to count every symbol
|
||||
// '~' is one of the last symbols in ascii table (except DEL)
|
||||
int count['~' - 32 + 1];
|
||||
resetArray(count);
|
||||
|
||||
int len = strlen(s);
|
||||
// Start of the current sequence
|
||||
int start = 0;
|
||||
// Result will be stored here
|
||||
int maxlen = 0;
|
||||
|
||||
while (start < len) {
|
||||
// End of the current sequence
|
||||
int end = start;
|
||||
|
||||
while (end < len) {
|
||||
// Calculate index in array
|
||||
int ch = s[end] - 32;
|
||||
// Symbol repeated
|
||||
if (count[ch] == 1) {
|
||||
// Fill array with 0
|
||||
resetArray(count);
|
||||
// Save max length
|
||||
int newmaxlen = end - start;
|
||||
if (newmaxlen > maxlen)
|
||||
maxlen = newmaxlen;
|
||||
// Move to the next sequence
|
||||
start++;
|
||||
end = start;
|
||||
}
|
||||
else {
|
||||
// Save the symbol
|
||||
count[ch]++;
|
||||
// Move to the next symbol
|
||||
end++;
|
||||
}
|
||||
}
|
||||
// Save max length
|
||||
int newmaxlen = end - start;
|
||||
if (newmaxlen > maxlen)
|
||||
maxlen = newmaxlen;
|
||||
// Move to the next sequence
|
||||
start++;
|
||||
end = start;
|
||||
}
|
||||
|
||||
return maxlen;
|
||||
}
|
3
problems/3-longest-substring/lib.h
Normal file
3
problems/3-longest-substring/lib.h
Normal file
|
@ -0,0 +1,3 @@
|
|||
#pragma once
|
||||
|
||||
int lengthOfLongestSubstring(char * s);
|
27
problems/3-longest-substring/main.c
Normal file
27
problems/3-longest-substring/main.c
Normal file
|
@ -0,0 +1,27 @@
|
|||
#include <stdio.h>
|
||||
#include "lib.h"
|
||||
|
||||
int main() {
|
||||
printf("Space: %d, z: %d\n", ' ', 'z');
|
||||
char* s1 = "abcabcbb";
|
||||
int res1 = lengthOfLongestSubstring(s1);
|
||||
printf("Test 1: %d\n", res1 == 3);
|
||||
|
||||
char* s2 = "bbbbb";
|
||||
int res2 = lengthOfLongestSubstring(s2);
|
||||
printf("Test 2: %d\n", res2 == 1);
|
||||
|
||||
char* s3 = "pwwkew";
|
||||
int res3 = lengthOfLongestSubstring(s3);
|
||||
printf("Test 3: %d\n", res3 == 3);
|
||||
|
||||
char* s4 = "";
|
||||
int res4 = lengthOfLongestSubstring(s4);
|
||||
printf("Test 4: %d\n", res4 == 0);
|
||||
|
||||
char* s5 = "a";
|
||||
int res5 = lengthOfLongestSubstring(s5);
|
||||
printf("Test 5: %d\n", res5 == 1);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue