No HashSet, no HashMap, no Array, only algorithm Java solution with O(n) complexity


  • 0
    X

    No HashSet, no HashMap, only algorithm Java solution with O(n) complexity.

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            int sLength = s.length();
    
            if (sLength <= 1) {
              return sLength;
            }
        
            int maxLength = 1, start = 0, pos;
            for (int i = 1; i < sLength; i ++) {
              int c = s.codePointAt(i);
              pos = s.indexOf(c, start);
              if (pos < 0 || pos >= i) {
                int l = pos - start + 1;
                maxLength = maxLength > l ? maxLength : l;
              } else {
                start = pos + 1;
              }
            }
            return maxLength;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.