Advertisement
jinhuang1102

14. Longest Common Prefix

Oct 17th, 2018
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. class Solution:
  2.     def longestCommonPrefix(self, strs):
  3.         """
  4.        :type strs: List[str]
  5.        :rtype: str
  6.        """
  7.         if not strs:
  8.             return ""
  9.        
  10.         if len(strs) == 1:
  11.             return strs[0]
  12.        
  13.         #记录第一个string
  14.         temp = strs[0]
  15.         for i in range(1, len(strs)):
  16.            
  17.             #与之后的每一个string进行比较的size,取较短的那个string的长度进行比较
  18.             j = 0
  19.             sz = min(len(temp), len(strs[i]))
  20.             while j < sz:
  21.                 if temp[j] != strs[i][j]:   #如果不相等了就把temp截短,然后break
  22.                     temp = temp[:j]
  23.                     break
  24.                 j = j + 1
  25.            
  26.             #For handle case ['aaa','a'], 就是说比较过的全部相等,但是长度不相等
  27.             temp = temp[:j]
  28.  
  29.             if temp == "":
  30.                 return temp
  31.            
  32.         return temp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement