yan chuanli 2 years ago
parent
commit
43133856dc
2 changed files with 83 additions and 6 deletions
  1. 42 0
      is_valid.py
  2. 41 6
      long_common_pre.py

+ 42 - 0
is_valid.py

@@ -0,0 +1,42 @@
+import pytest
+def isValid(s: str):
+    lens = len(s)
+    if lens % 2 == 1:
+        return False
+
+    dic = {
+        "(": ")",
+        "[": "]",
+        "{": "}"
+    }
+
+    # 栈
+    list = []
+    for i in s:
+        if i in dic.keys():
+            list.append(i)
+        else:
+            # if len(list) ==0 or i != dic.get(list[-1]):
+            if len(list) == 0 or i != dic.get(list[-1]):
+                list.append(i)
+            else:
+                list.pop()
+
+    if len(list) == 0:
+        return True
+    else:
+        return False
+
+
+@pytest.mark.parametrize(
+    "s, expect",
+    [
+        ("()[]", True)
+    ]
+)
+def test_cases(s, expect):
+    assert isValid(s) == expect
+
+
+
+

+ 41 - 6
long_common_pre.py

@@ -1,13 +1,48 @@
 from typing import List
+import pytest
+def commonPrefix(str1, str2):
+    flag = 0
+    if len(str1) >= len(str2):
+        shorter = str2
+        longer = str1
+    else:
+        shorter = str1
+        longer = str2
+
+    for i in range(len(shorter)):
+        if shorter[i] == longer[i]:
+            flag += 1
+        else:
+            break
+
+    return shorter[0:flag]
 
 def longestCommonPrefix(strs: List[str]):
-    res = ""
-    lcs = ""
+    if strs == "":
+        return ""
+    prefix = strs[0]
     lens = len(strs)
-    for i in range(lens):
-        if len(strs[i]) < len(strs[i+1]):
-            lcs = strs[i]
-            num = i
+    for i in range(1, lens):
+        prefix = commonPrefix(prefix, strs[i])
+        if prefix == "":
+            break
+    return prefix
+
+@pytest.mark.parametrize(
+    "strs, expect",
+    [
+        (["car", "racecar", "dog"], ""),
+        (["flower", "flow", "flight"], "fl"),
+        (["ba", "ca", "da"], ""),
+        (["aa", ""], ""),
+        (["aaa"], "aaa")
+    ]
+)
+def test_cases(strs, expect):
+    assert longestCommonPrefix(strs) == expect
+
+
+