fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class Solution {
  7. public:
  8. int lengthOfLongestSubstring(const vector<int>& arr) {
  9. int n = arr.size();
  10. int maxLength = 0;
  11. vector<int> charIndex(128, -1);
  12. int left = 0;
  13.  
  14. for (int right = 0; right < n; right++) {
  15. if (charIndex[arr[right]] >= left) {
  16. left = charIndex[arr[right]] + 1;
  17. }
  18. charIndex[arr[right]] = right;
  19. maxLength = max(maxLength, right - left + 1);
  20. }
  21.  
  22. return maxLength;
  23. }
  24. };
  25.  
  26. int main() {
  27. Solution sol;
  28. int n;
  29. cin >> n; // Read the length of the array
  30. vector<int> arr(n);
  31.  
  32. // Read each character into the vector
  33. for (int i = 0; i < n; i++) {
  34. cin >> arr[i];
  35. }
  36.  
  37. int result = sol.lengthOfLongestSubstring(arr);
  38. cout << "Length of longest substring without repeating characters: " << result << endl;
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.01s 5280KB
stdin
10
1 2 3 4 1 3 8 4 6 7
stdout
Length of longest substring without repeating characters: 6