首页 > 代码库 > 『LeetCode』练习第二弹

『LeetCode』练习第二弹

3. Longest Substring Without Repeating Characters

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 subsequence and not a substring.

 1 class Solution(object):
 2     def lengthOfLongestSubstring(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         l = len(s)
 8 
 9         # 单个字符或空字符直接返回
10         if l == 1:
11             return 1
12         elif l == 0:
13             return 0
14 
15         res = []
16         for i in range(l):
17             for j in range(i + 1, l):
18                 if s[j] in s[i:j]:
19                     print(s[i:j])
20                     res.append(len(s[i:j]))
21                     break
22                 # j是最后一个字符时直接跳出循环来不及计数手动+1
23                 elif j==l-1:
24                     print(s[i:j])
25                     res.append(len(s[i:j])+1)
26         return max(res)

结果:算法没什么问题,问题是又又又超时了T_T

有关子串和子序列:

      子串:子串是必须在原字符串中可以找到的,asd中的sd是子串。

       子序列:子序列可以拆分,asd中的ad就是子序列,sd既是子串又是子序列。

 

4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
 1 class Solution(object):
 2     def findMedianSortedArrays(self, nums1, nums2):
 3         """
 4         :type nums1: List[int]
 5         :type nums2: List[int]
 6         :rtype: float
 7         """
 8         nums = nums1 + nums2
 9         nums = sorted(nums)
10         l = len(nums)
11         if l % 2 == 0:
12             return (nums[int(l/2-1)]+nums[int(l/2)])/2.0
13         else:
14             return (nums[int((l-1)/2)])

结果:Accepted~~虽然标注是hard难度,但是对python来讲这种计算简直太简单了,不过要是用c估计会很麻烦...又想起了写的我头皮发麻的研究生复试机考...没错就是c...

补充一点:

      对于非硬性要求的环境,我倾向于使用3.x版本而不是2.7,而这里默认编译器是2.7,所以有一点细节要处理,2.7默认除法继承操作数类型,3.x默认浮点型,所以会有int()(为了3.x可以运行)和/2.0(为了2.7可以运行)的类型转换处理。

『LeetCode』练习第二弹