Advertisement
DhruvSaraswat

Ola Krutrim iOS Interview on 17th July 2024

Jul 17th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. OPTIMAL APPROACH :-
  2. func longestSubstringLength(inputString: String) -> Int {
  3. guard inputString.count > 0 else { return 0 }
  4.  
  5. var longestSubstringLength = 0
  6. var leftIndex = 0
  7. var rightIndex = 0
  8. let inputStringArray = Array(inputString)
  9.  
  10. var set = Set<Character>()
  11.  
  12. while rightIndex < inputString.count {
  13. if !set.contains(inputStringArray[rightIndex]) {
  14. set.insert(inputStringArray[rightIndex])
  15. rightIndex += 1
  16. longestSubstringLength = max(longestSubstringLength, rightIndex - leftIndex)
  17. } else {
  18. while set.contains(inputStringArray[leftIndex]) {
  19. set.remove(inputStringArray[leftIndex])
  20. leftIndex += 1
  21. }
  22. }
  23. }
  24.  
  25. return longestSubstringLength
  26. }
  27.  
  28. BRUTE FORCE APPROACH :-
  29. import Foundation
  30.  
  31. func longestSubstringLengthBruteForce(inputString: String) -> Int {
  32. let inputStringArray = Array(inputString)
  33.  
  34. for i in 0 ..< inputString.count {
  35. for j in stride(from: inputString.count - 1, through: i, by: -1) {
  36. let subString = String(inputStringArray[i ... j])
  37. print(subString)
  38. if doesSubstringHaveUniqueChars(inputString: subString) {
  39. return subString.count
  40. }
  41. }
  42. }
  43.  
  44. return 0
  45. }
  46.  
  47. func doesSubstringHaveUniqueChars(inputString: String) -> Bool {
  48. let inputStringArray = Array(inputString)
  49. var set = Set<Character>()
  50.  
  51. for i in 0 ..< inputString.count {
  52. if set.contains(inputStringArray[i]) {
  53. return false
  54. }
  55. set.insert(inputStringArray[i])
  56. }
  57.  
  58. return true
  59. }
  60.  
  61. print("Longest substring length = \(longestSubstringLengthBruteForce(inputString: "pwwkew"))")
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement