正则匹配顺序连续或者倒序连续的字符串及其相应的个数

面试中遇到这样一道题,有一个字符串,"12345678abcABCDefghijk9874321YXWV321",现在定义同类型字符(数字为一类型,大写字母为一类型,小写字母为一类型)4个及4个以上为连续,需要找出连续(包括顺序连续和倒序连续)的个数,请问一下各位大神这个应该怎么解决呢?谢谢。

偶然的你
浏览 695回答 2
2回答

墨色风雨

连续的意思是上一个字符和下一个字符的ascii值相差1,并且连续出现4次和以上。这个貌似c语言作业...java代码:String str = "12345678abcABCDefghijk9874321YXWV321";&nbsp; &nbsp; &nbsp; &nbsp; char f=str.charAt(0);&nbsp; &nbsp; &nbsp; &nbsp; int count = 0;&nbsp; &nbsp; &nbsp; &nbsp; for(int i=1 ; i < str.length(); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char c = str.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(c-f == 1 || f-c==1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++count;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(count >= 3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(&nbsp; str.substring(&nbsp; i-count-1 ,i)&nbsp; ) ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f=c;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }

侃侃尔雅

function trans (str) {&nbsp; let before = ''&nbsp; let len = 0&nbsp; let order = null&nbsp; let matched = []&nbsp; for (let i = 0, length = str.length; i < length; i++) {&nbsp; &nbsp; let cur = str[i]&nbsp; &nbsp; if (len === 0) {&nbsp; &nbsp; &nbsp; before = cur&nbsp; &nbsp; &nbsp; len = 1&nbsp; &nbsp; &nbsp; order = null&nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; }&nbsp; &nbsp; let diff = cur.charCodeAt(0) - before.charCodeAt(0)&nbsp; &nbsp; if (Math.abs(diff) === 1) {&nbsp; &nbsp; &nbsp; order = order || diff&nbsp; &nbsp; &nbsp; if (order === diff) {&nbsp; &nbsp; &nbsp; &nbsp; len += 1&nbsp; &nbsp; &nbsp; &nbsp; before = cur&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (len >= 4) {&nbsp; &nbsp; &nbsp; matched.push(str.slice(i - len, i))&nbsp; &nbsp; }&nbsp; &nbsp; before = cur&nbsp; &nbsp; len = 1&nbsp; &nbsp; order = null&nbsp; }&nbsp; if (len >= 4) {&nbsp; &nbsp; matched.push(str.slice(str.length - len))&nbsp; }&nbsp; return {&nbsp; &nbsp; count: matched.length,&nbsp; &nbsp; matched&nbsp; }}trans("12345678abcABCDefghijk9874321YXWV321").count
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript