鍍金池/ 問答/Java  HTML/ 正則匹配順序連續(xù)或者倒序連續(xù)的字符串及其相應的個數(shù)

正則匹配順序連續(xù)或者倒序連續(xù)的字符串及其相應的個數(shù)

面試中遇到這樣一道題,有一個字符串,"12345678abcABCDefghijk9874321YXWV321",現(xiàn)在定義同類型字符(數(shù)字為一類型,大寫字母為一類型,小寫字母為一類型)4個及4個以上為連續(xù),需要找出連續(xù)(包括順序連續(xù)和倒序連續(xù))的個數(shù),請問一下各位大神這個應該怎么解決呢?謝謝。

回答
編輯回答
心上人

連續(xù)的意思是上一個字符和下一個字符的ascii值相差1,并且連續(xù)出現(xiàn)4次和以上。這個貌似c語言作業(yè)...

java代碼:

String str = "12345678abcABCDefghijk9874321YXWV321";
        char f=str.charAt(0);
        int count = 0;
        for(int i=1 ; i < str.length(); ++i) {
            char c = str.charAt(i);
            if(c-f == 1 || f-c==1) {
                ++count;
            }else {
                if(count >= 3) {
                    System.out.println(  str.substring(  i-count-1 ,i)  ) ;
                }
                count = 0;
            }
            f=c;
            
        }
2018年2月12日 09:47
編輯回答
氕氘氚
function trans (str) {
  let before = ''
  let len = 0
  let order = null
  let matched = []
  for (let i = 0, length = str.length; i < length; i++) {
    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
2018年8月6日 10:32