Length of the Longest Alphabetical Continuous Substring - Compare Adjacent [JS]

Description 

Solution: Compare Adjacent

Compare adjacent characters and keep track of the length of the current continuous string.
Record the maximum length.

Time Complexity: O(n)
Space Complexity: O(1)

var longestContinuousSubstring = function(s) {
  let n = s.length, count = 1, ans = 1;
  for (let i = 1; i < n; i++) {
    let currCharcode = s.charCodeAt(i);
    let prevCharcode = s.charCodeAt(i - 1);
    if (currCharcode - prevCharcode === 1) count++;
    else count = 1;
    ans = Math.max(ans, count);
  }
  return ans;
};

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]