Browse Source

Add longest substring

Snow 8 years ago
parent
commit
55e2c9ea92
1 changed files with 26 additions and 0 deletions
  1. 26 0
      arrays-and-strings/longest_substring.py

+ 26 - 0
arrays-and-strings/longest_substring.py

@@ -0,0 +1,26 @@
+# Given a string, find the length of the longest substring without repeating characters.
+import pytest
+
+def test_longest_substring():
+    cases = ['a', 'aaaa','pwdkee', 'asdfghjkl']
+    expected = [1, 1, 5, 9]
+    for c,e in zip(cases,expected):
+        assert longest_substring(c) == e
+
+def longest_substring(s):
+    len_s = len(s)
+    if len_s <= 1:
+        return len_s
+    len_longest = 0
+    sub_str = []
+    for i in range(len_s):
+        for j in range(i,len_s):
+            if s[j] not in sub_str:
+                sub_str.append(s[j])
+            else:
+                i = j
+                if len(sub_str) > len_longest:
+                    len_longest = len(sub_str)
+                    sub_str = []
+                break
+    return len_longest