Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- OPTIMAL APPROACH :-
- func longestSubstringLength(inputString: String) -> Int {
- guard inputString.count > 0 else { return 0 }
- var longestSubstringLength = 0
- var leftIndex = 0
- var rightIndex = 0
- let inputStringArray = Array(inputString)
- var set = Set<Character>()
- while rightIndex < inputString.count {
- if !set.contains(inputStringArray[rightIndex]) {
- set.insert(inputStringArray[rightIndex])
- rightIndex += 1
- longestSubstringLength = max(longestSubstringLength, rightIndex - leftIndex)
- } else {
- while set.contains(inputStringArray[leftIndex]) {
- set.remove(inputStringArray[leftIndex])
- leftIndex += 1
- }
- }
- }
- return longestSubstringLength
- }
- BRUTE FORCE APPROACH :-
- import Foundation
- func longestSubstringLengthBruteForce(inputString: String) -> Int {
- let inputStringArray = Array(inputString)
- for i in 0 ..< inputString.count {
- for j in stride(from: inputString.count - 1, through: i, by: -1) {
- let subString = String(inputStringArray[i ... j])
- print(subString)
- if doesSubstringHaveUniqueChars(inputString: subString) {
- return subString.count
- }
- }
- }
- return 0
- }
- func doesSubstringHaveUniqueChars(inputString: String) -> Bool {
- let inputStringArray = Array(inputString)
- var set = Set<Character>()
- for i in 0 ..< inputString.count {
- if set.contains(inputStringArray[i]) {
- return false
- }
- set.insert(inputStringArray[i])
- }
- return true
- }
- print("Longest substring length = \(longestSubstringLengthBruteForce(inputString: "pwwkew"))")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement