Regular matching sequential or reverse continuous strings and their corresponding number

interview encountered such a question, there is a string, "12345678abcABCDefghijk9874321YXWV321", now define the same type of characters (numbers for one type, uppercase letters for one type, lowercase letters for one type) for 4 or more consecutive, need to find out the number of consecutive (including sequential and reverse continuous), I would like to ask you how to solve this? Thank you.


continuous means that the ascii value of the previous character is 1 different from that of the next character, and it appears 4 or more times in a row. This looks like a c language assignment.

java Code:

String str = "12345678abcABCDefghijk9874321YXWV321";
        char f=str.charAt(0);
        int count = 0;
        for(int i=1 ; i < str.length(); PPi) {
            char c = str.charAt(i);
            if(c-f == 1 || f-c==1) {
                PPcount;
            }else {
                if(count >= 3) {
                    System.out.println(  str.substring(  i-count-1 ,i)  ) ;
                }
                count = 0;
            }
            f=c;
            
        }

function trans (str) {
  let before = ''
  let len = 0
  let order = null
  let matched = []
  for (let i = 0, length = str.length; i < length; iPP) {
    let cur = str[i]
    if (len === 0) {
      before = cur
      len = 1
      order = null
      continue
    }

    let diff = cur.charCodeAt(0) - before.charCodeAt(0)
    if (Math.abs(diff) === 1) {
      order = order || diff
      if (order === diff) {
        len += 1
        before = cur
        continue
      }
    }
    if (len >= 4) {
      matched.push(str.slice(i - len, i))
    }
    before = cur
    len = 1
    order = null
  }
  if (len >= 4) {
    matched.push(str.slice(str.length - len))
  }

  return {
    count: matched.length,
    matched
  }
}
trans("12345678abcABCDefghijk9874321YXWV321").count

happens to be learning rules recently. I think it's appropriate to use regular matching
let str = "12345678abcABCDefghijk9874321YXWV321"
let aa = str.match (/ d {4,} / g)
let bb = str.match (/ [Amurz] {4,} / g)
let cc = str.match (/ [arelz] {4,} / g)
returns arrays that match numbers, uppercase and lowercase, respectively.

Menu