- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static java.lang.System.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class Rep implements CharSequence
{
String str = null;
int len;
char base;
public Rep(char x, int count)
{
this.len = count;
this.base = x;
}
@Override
public int length()
{
return len;
}
@Override
public char charAt(int index)
{
return base;
}
@Override
public CharSequence subSequence(int beginIndex, int endIndex)
{
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > this.len) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == this.len)) ? this
: new Rep(this.base, subLen);
}
@Override
public String toString()
{
return null!=str ? str : (this.str = new String(new char[]{base}).repeat(len));
}
public static void main(String... args)
{
long ns = 0L;
Pattern lazy = Pattern.compile("^(11+?)\\1+$");
Pattern greedy = Pattern.compile("^(11+?)\\1+$");
ns=nanoTime(); lazy .matcher(new Rep('1',100160079)).matches(); out.println( NANOSECONDS.toMillis(nanoTime()-ns));
ns=nanoTime(); greedy.matcher(new Rep('1',100160079)).matches();out.println( NANOSECONDS.toMillis(nanoTime()-ns));
ns=nanoTime(); greedy.matcher(new Rep('1',1165139)).matches();out.println( NANOSECONDS.toMillis(nanoTime()-ns));
ns=nanoTime(); "1".repeat( 100160079 ).matches("^(11+?)\\1+$") ; out.println("Lazy String:"+ NANOSECONDS.toMillis(nanoTime()-ns));
ns=nanoTime(); "1".repeat( 100160079 ).matches("^(11+)\\1+$") ; out.println("Greedy String:"+ NANOSECONDS.toMillis(nanoTime()-ns));
}
}
Follow us!