检查字符串数组中的回文的运行时
runtime of checking an array of strings for palindromes
我编写了一个函数来查找字符串数组中的回文。起初,我循环遍历数组,检查每个项目,看看它是否是一个带有辅助函数的回文,该函数检查数组中每个索引处的单词(按字母)——这是O(n^2)正确吗?
然后我改变了我的方法,弹出数组(把它当作堆栈处理),然后检查这一项是否是回文,并在array.length的整个数组中这样做。这是O(n),对吗?
'use strict';
function isTextPalindrome(text) {
//this ignores anything other than letters
text = text.replace(/[^a-zA-Z]/g, '').toLowerCase();
// console.log(text);
if (!text) {
return "There must be text as an input!";
}
var left = 0;
var right = text.length - 1;
while (left < right) {
if (text[left++] !== text[right--]) {
return false;
}
}
return true;
}
// console.log(isTextPalindrome('race car'));
function palindromesInArray(arr) {
var popped;
var count = 0;
//treat the array as a stack. don't loop through, just pop off one at a time to avoid extra run time cost.
while (popped = arr.pop()) {
if (typeof (popped) !== 'string') {
return "Only works on strings";
}
if (isTextPalindrome(popped)) {
count++;
}
}
// for (let i = 0; i < arr.length; i++) {
// if (typeof (arr[i]) !== 'string') {
// return "Only works on strings";
// }
// if (isTextPalindrome(arr[i])) {
// count++;
// }
// }
return count;
}
console.log(palindromesInArray(['mom', 'race car', 'dad', 'abba', 'redivider', 'noon', 'civic', 'level', 'blah'])) // returns 8
console.log(palindromesInArray(['mom', 'race car', 'dad', 'blah'])); // returns 3
这里所说的O(n)
是什么意思还不清楚(请记住,O(n)
表示相对于输入长度的计算增长)。这里不清楚你想数多少。
如果您的n
是字符串数组中所有字符长度的总和,那么两种算法都是O(n)
。如果有n
(字符串的长度)和m
(数组中字符串的数量),则有O(nm)
。
检查长度为m
的字符串的回文是O(m)
。
简单地在长度为n
的数组(或堆栈)上循环就是O(n)
。
如果最大字符串长度为n
,则同时执行这两个操作仅为O(n^2)
。否则,它是O(n*m)
相关文章:
- 使用压缩的JavaScript文件(不是运行时压缩)
- 如何在运行时在angular 2中加载外部js脚本
- JavaScript错误:Microsoft JScript运行时错误:应为对象
- Google 脚本:用于创建日历活动的脚本运行时不会出错,但不会执行任何操作
- http.listen()在运行时接受终端命令
- 自定义运行时Can'在谷歌应用引擎中看不到我的自定义日志
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- JavaScript运行时是如何工作的
- 在运行时创建元素时移到一边时出错
- 在php中的运行时添加文本字段
- 检查字符串数组中的回文的运行时
- 在任何ajax回调中出现运行时错误后,ajaxStop事件停止激发
- JavaScript在模糊时将默认值填充回文本字段
- 如何附加点击事件在运行时,当我有一个数组中的所有id得到填充时,文档准备好了
- 使用文档时,在DOM加载后添加的按钮上单击事件不运行
- 如何在第一次运行时更新回调视图
- 环回错误:找不到模型:Book:当我使用命令创建新模型后尝试运行时
- jQuery动画在运行时触发回调两次
- Node.js - 如果我在 I/O 和回调仍在运行时调用 response.end 会发生什么
- 如何在运行时添加脚本?(文档.Write不是一个函数)