贪婪与非贪婪搜索的复杂性

时间:2019-05-29 05:19:13

标签: algorithm time-complexity big-o complexity-theory space-complexity

给出以下字符串:

  

敏捷的棕色狐狸跳过了那只懒惰的狗。   跳过那条懒惰的狗。敏捷的棕色狐狸跳过了那条懒惰的狗。   快棕色的狐狸跳过了那只懒惰的狗。   跳过那条懒惰的狗。敏捷的棕色狐狸跳过了那条懒惰的狗。   那只快活的棕狐跳过了那只懒狗。

如果我们使用以下两个表达式搜索“ fox”:

([\s\S].*?)(fox)

([\s\S].*?)(fox)*

要考虑哪些关键的复杂性点(时间,空间,大O)?

DEMO for less greedy version

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
	const regex = /([\s\S].*?)(fox)/gm;
	const str = `The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.`;
	const subst = `$2\n`;

	var match = str.replace(regex, subst);
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");

DEMO for more greedy version

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
	const regex = /([\s\S].*?)(fox)*/gm;
	const str = `The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.The quick brown fox jumped over the lazy dog.`;
	const subst = `$2`;

	var match = str.replace(regex, subst);
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");

0 个答案:

没有答案