繁体   English   中英

如何左右移动字符串的字符,每当出现特定字符时计数?

[英]How to move left and right through characters of a string, counting whenever a specific character appear?

如果我有一条路作为字符串 S,S 中的每个字符是:

 "<" -> car going to the left 
 ">" -> car going to the right 
 "." -> speed camera

如何计算汽车通过测速摄像头的总次数? 考虑到向右行驶的汽车只会经过右侧的摄像头,而向左行驶的汽车只会经过左侧的摄像头。

测试让我写一个function: function solution(S); 给定一个长度为 N 的字符串 S,返回汽车经过相机的总次数。 例子:

Given S = ".>..." , the function should return 3.
Given S = ".>.<.>" , the function should return 4.
Given S = ">>>.<<<" , the function should return 6.

我试图使用 2 个指针在 Javascript 中解决这个问题,但卡住了,没时间了。 有什么建议吗? 在 Javascript 中解决这个问题的好方法是什么?

谢谢你。

使用嵌套循环。 主循环查找<>字符。 当它看到其中之一时,它会执行第二个循环来计算. 它之前或之后的字符,将其添加到总数中。

 function solution(s) { let count = 0; for (let i = 0; i < s.length; i++) { if (s[i] == '<') { for (let j = 0; j < i; j++) { if (s[j] == '.') { count++; } } } else if (s[i] == '>') { for (let j = i + 1; j < s.length; j++) { if (s[j] == '.') { count++; } } } } return count; } console.log(solution(".>...")); console.log(solution(".>.<.>")); console.log(solution(">>>.<<<"));

这是简单的解决方案,不是很有效(它是 O(n^2))。 因此,如果您尝试为代码挑战站点执行此操作,则可能会出现超出时间限制的失败。

你可以做两次通过,一次计算左行汽车经过相机的次数,而另一次计算右行汽车经过的次数。 时间复杂度为 O(n)。

 function solution(s) { let res = 0; for (let i = 0, cnt = 0; i < s.length; ++i) if (s[i] == '.') cnt++; else if (s[i] == '<') res += cnt; for (let i = s.length-1, cnt = 0; i >= 0; --i) if (s[i] == '.') cnt++; else if (s[i] == '>') res += cnt; return res; } console.log(solution(".>...")); console.log(solution(".>.<.>")); console.log(solution(">>>.<<<"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM