[Algorithm] Coding Interview Question and Answer: Longest Consecutive Characters

Given a string, find the longest subsequence consisting of a single character. Example: longest("ABAACDDDBBA") should return {'D': 3}.

 

const str = "AABCDDBBBEA";

function longest (str) {
  let max_count = 0, count = 0, max_char = null, prv_char = null;
  
  for (let current of str) {
    if (current === prv_char) {
      count++
    } else {
      count = 1;
    }

    if (count > max_count) {
      max_count = count;
      max_char = current;
    }

    prv_char = current;
  }

  return {[max_char]: max_count};
}

console.log(longest(str)) // {B: 3}

 

 

转载于:https://www.cnblogs.com/Answer1215/p/10448061.html

你可能感兴趣的:([Algorithm] Coding Interview Question and Answer: Longest Consecutive Characters)