带有内部 while 循环的 while 循环:O(n) 或 O(n^2)?

While loop with inner while loop: O(n) or O(n^2)?

#include <unordered_map>
using namespace std;

        int lengthOfLongestSubstring(string s) {
            
            unordered_map<char, int> ht;
            int max = 0;
            
            int i = 0; int j = 0; 
            while (i < s.size() && j < s.size()) {
                
                if (ht.find(s.at(j)) == ht.end()) {
                    ht.insert( {s.at(j), j} );
                    max = (j - i + 1 > max) ? j - i + 1 : max;
                    j++;
                }
                else {
                    int len = ht.at(s.at(j)) + 1;
                    while(i < len) {
                        ht.erase(s.at(i));
                        i++;
                    }
                    
                }
                
            }
            
            return max;
        }

时间复杂度是O(n)还是O(n^2)?为什么?

我的直觉是它是 O(n),i 和 j 迭代相同的长度。

是:

  • 严格来说:O(2n),在最坏的情况下,你迭代输入大小的两倍;
  • 渐近语言说话:O(n),因为忽略常数因子is