leetcode选题:
3. Longest Substring Without Repeating Characters
Description:
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.
思路:
定义一个从字符到下标的字典(即映射),在寻找区间[i, j] 中一旦发现某字符已经在字典中,且下标为k,就将该字符对应的下标改为j。计算最新子串长度为j - i + 1,并更新[i, j] 为 [k+1, j]。
解法:
1. 以 j 为下标,for循环遍历s
2. 若字典中存在 s[j] , 则取s[j] 对应的下标和 i 两者之间的最大值为 i 的新值,否则 i 不变
3. 取res的值为现阶段 res 和 j - i + 1 之间的最大值
4. 将最新的 s[j] 放入字典中,value为 j+1
5. 待for循环结束,返回res的值
代码:
# -*- coding:utf-8 -*-
class Solution:
def lengthOfLongestSubstring(self, s):
res = 0
i = 0
dic = {}
for j in range(len(s)):
i = max(dic[s[j]], i) if s[j] in dic else i
res = max(res, j - i + 1)
'''下标为j+1而不是j的原因,是因为当s[i]==s[j]时,
j-i+1其实比子串的长度多了1位,因为它算入了首位两个重复的字符'''
dic[s[j]] = j + 1
return res
461. Hamming Distance
Description:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 2^31.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
(从左往右,第二位和第四位不同)
The above arrows point to positions where the corresponding bits are different.
思路:
题中所说的“hamming distance”可理解为两个整数的二进制形式进行异或操作以后,得到的二进制结果中“1”的数目。所以,先得到两数异或所得的二进制数,再对其计算“1”的数目即可。
解法:
1. 对两数进行异或操作
2. 将异或结果转换为二进制的字符串形式
3. 计算该字符串中“1”出现的次数
通过查询可知,python内置函数bin()可以将一个整数传换成一个以”0b”开头的二进制字符串,且字符串类型的函数count()可以统计字符串里某个字符出现的次数。
代码:
class Solution:
def hammingDistance(self, x, y):
return bin(x^y).count('1')