gpt4 book ai didi

javascript - JS 跳出嵌套 for 循环

转载 作者:行者123 更新时间:2023-12-02 14:12:12 26 4
gpt4 key购买 nike

为以下算法问题编写代码,但不知道为什么它不起作用。在调试器之后,我发现 elem 变量永远不会迭代超出“s”。我担心这可能是因为我对如何打破父 for 循环的理解。我读这个问题:Best way to break from nested loops in Javascript?但我不确定我是否做错了什么。

function firstNonRepeatingLetter(s) {
//input string
//return first character that doesn't repeat anywhere else.
//parent for loop points to the char we are analyzing
//child for loop iterates over the remainder of the string
//if child for loop doesnt find a repeat, return the char, else break out of the child for loop and cont

if (s.length == 1) { return s;}

parent_loop:
for (var i = 0; i < s.length - 1; i++){ //parent loop
var elem = s[i];
child_loop:
for (var j = i + 1; j < s.length; j++){
if (elem == s[j]){
break child_loop;
}
}
return s[i];
}
return "";
}

console.log(firstNonRepeatingLetter('stress')); // should output t, getting s.

最佳答案

我的建议是使用单个 for 循环而不是使用两个循环。

for( var i = 0; i<s.length - 1;i++) {
var lastIndex = s.lastIndexOf(s[i]);
if ( lastIndex == i) {
return s[i];
}
}

关于javascript - JS 跳出嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com