class Solution { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var valKeyMap: Dictionary<Int, Int> = Dictionary<Int, Int>() for (idx,val) in nums.enumerated() { let other_target = target - val if let ot = valKeyMap[other_target] { if ot != idx { return [idx,ot] } } valKeyMap[val] = idx } return [] } }
var outCarrer = l1?.next var outCarrer2 = l2?.next var lasttenths = 0 let sum = l1!.val + l2!.val if sum > 9 { lasttenths = 1 } let newList:ListNode? = ListNode(sum % 10) var inCarrer = newList while outCarrer != nil || outCarrer2 != nil{ var val1 = 0 var val2 = 0 if let v = outCarrer?.val { val1 = v } if let v = outCarrer2?.val { val2 = v } let sum = val1 + val2 + lasttenths lasttenths = sum > 9 ? 1 : 0 let sum2 = sum % 10 inCarrer?.next = ListNode(sum2) outCarrer = outCarrer?.next outCarrer2 = outCarrer2?.next inCarrer = inCarrer?.next } if lasttenths != 0{ inCarrer?.next = ListNode(1) } return newList } }
public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); int ans = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j <= n; j++) if (allUnique(s, i, j)) ans = Math.max(ans, j - i); return ans; }
public boolean allUnique(String s, int start, int end) { Set<Character> set = new HashSet<>(); for (int i = start; i < end; i++) { Character ch = s.charAt(i); if (set.contains(ch)) return false; set.add(ch); } return true; } }
方法2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); Set<Character> set = new HashSet<>(); int ans = 0, i = 0, j = 0; while (i < n && j < n) { // try to extend the range [i, j] if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); ans = Math.max(ans, j - i); } else { set.remove(s.charAt(i++)); } } return ans; } }
方法3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } }