给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
这道题这里用Java和swift写,发现的问题及要知道的Java基础知识点:
首先我们应该清楚这个概念:这里的有序和无序不是指集合中的排序,而是是否按照元素添加的顺序来存储对象。
list是按照元素的添加顺序来存储对象的,因此是有序的。他的实现类ArrayList、LinkedList、Vector都是有序的。
Map是无序的,它的存储结构是哈希表<key,value>键值对,map中插入元素是根据key计算出的哈希值来存储元素的,因此他不是按照元素的添加顺序来存储对象的,所以Map是无序的。它的实现类有:HashMap、TableMap和TreeMap。
其中LinkedHashMap是有序的,hashMap用来保证存储的值键值对,list用来保证插入的顺序和存储的顺序一致。
Set是无序的,并且set中的元素不能重复。set的底层实现其实是Map,它是计算key的哈希值来确定元素在数组中的存放位置,所以是无序的,因为在Map中key的值不能重复,所以set中的元素不能重复。它的实现类有:haseSet、TreeSet。
其中LinkedHashSet是有序的,其中haseSet用来保证数据唯一,List用来保证插入的顺序和存储的顺序一致。
public int lengthOfLongestSubstring(String s) {
// 哈希集合,记录每个字符是否出现过
Set<Character> set = new HashSet<Character>();
int n = s.length();
// rightIndex为右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
int rightIndex = -1, result = 0;
for (int i = 0; i < n; i++) {
if (i != 0) {
// 左指针向右移动一格,移除一个字符
set.remove(s.charAt(i-1));
}
while (rightIndex + 1 < n && !set.contains(s.charAt(rightIndex + 1))) {
// 不断地移动右指针
set.add(s.charAt(rightIndex + 1));
rightIndex++;
}
// 第 i 到 rightIndex 个字符是一个极长的无重复字符子串
result = Math.max(rightIndex - i + 1, result);
}
return result;
}
// aaa
class ABC {
func lengthOfLongestSubstring(_ s: String) -> Int {
let len = s.count
var rightIndex = -1, result = 0
var set = Set<Character>()
for i in 0..<s.count {
if i > 0 {
set.remove(s[i-1])
}
while (rightIndex + 1 < len && !set.contains(s[rightIndex + 1])) {
set.insert(s[rightIndex + 1])
rightIndex += 1
}
result = max(result, rightIndex - i + 1)
}
return result
}
}
extension String {
subscript(i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
}
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0 ; i < nums.length - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i-1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
while(left < right && nums[right] == nums[--right]);
}else if (sum < 0) {
while(left < right && nums[left] == nums[++left]);
}else{
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while(left<right && nums[left] == nums[++left]);
while(left<right && nums[right] == nums[--right]);
}
}
}
return res;
}