的JavaScript(ES6) - 147个 133 136特性
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
期望要测试的字符串在变量中,s
然后将结果输出到控制台。
var repetitionRE = /^(((.*).*)\2+)\3\n/;
// Regular expression to find repeating sequence
// without any trailing sub-string of the sequence.
var sequence = repetitionRE.exec(s)[1]; // Find the sequence string.
s.split('\n') // Split the input into an array.
.map(
( row, index ) => // Anonymous function using ES6 arrow syntax
{
var testStr = row + '᛫'+ sequence + sequence;
// Concatenate the current row, a character which won't
// appear in the input and two copies of the repetitions
// of the sequence from the first line.
var match = /^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(testStr);
// Left of the ᛫ finds sub-matches for a single
// character and the sub-strings before and after.
// Right of the ᛫ looks for any number of characters
// then the before and after sub-matches with a
// different character between.
if ( match )
console.log( match[1].length, index );
// Output the index of the non-matching character
// and the row.
}
);
测试用例1
s="codegolfcodegolfco\negolfcodegolfcodeg\nlfcodegolfcodegoff\nodegolfcodegolfcod\ngolfcodegolfcodego\nfcodegolfcodegolfc"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
产出
16 2
测试案例2
s="][[][][[][][[][][[][][[\n[][][[][][[][][[][][[][\n[][[][][[][][[][][[][][\n[[][][[]]][[][][[][][[]"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
产出
8 3
测试案例3
s="...\n. .\n..."
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
产出
1 1
测试案例4
s="ababa\nbabab\nababb\nbabab"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
产出
4 2
测试案例5
s="xyxy\nyyxy"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
产出
0 1
测试案例6
s="ababaababa\nababaaaaba"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))
产出
6 1