diff --git a/longest-substring-without-repeating-characters/sonjh1217.swift b/longest-substring-without-repeating-characters/sonjh1217.swift new file mode 100644 index 000000000..a3072a91a --- /dev/null +++ b/longest-substring-without-repeating-characters/sonjh1217.swift @@ -0,0 +1,19 @@ +class Solution { + // O(n) time / O(n) space + func lengthOfLongestSubstring(_ s: String) -> Int { + var lastIndexByCharacter = [Character: Int]() + var start = 0 + var maxLenth = 0 + + for (i, character) in s.enumerated() { + if let lastIndex = lastIndexByCharacter[character], + lastIndex >= start { + start = lastIndex + 1 + } + lastIndexByCharacter[character] = i + maxLenth = max(maxLenth, i - start + 1) + } + return maxLenth + } +} + diff --git a/reverse-linked-list/sonjh1217.swift b/reverse-linked-list/sonjh1217.swift new file mode 100644 index 000000000..36fd1a0b1 --- /dev/null +++ b/reverse-linked-list/sonjh1217.swift @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + // O(n) time / O(1) space + func reverseList(_ head: ListNode?) -> ListNode? { + var node = head + var lastNode: ListNode? = nil + + while node != nil { + let next = node?.next + node?.next = lastNode + lastNode = node + node = next + } + + return lastNode + } +}