다음 알고리즘 문제에 대한 코드를 작성하고 작동하지 않는 이유를 알지 못합니다. 디버거 다음에, 나는 elem 변수가 's'를 반복하지 않는다는 것을 발견했다. 부모님을 위해 for 루프를 깨는 방법을 이해했기 때문에 이것이 가능할 수 있다고 우려했습니다. 나는 이 질문을 읽었다 : Best way to break from nested loops in Javascript? 그러나 나는 아마 내가 뭔가 잘못하고 있는지 확실하지 않다. 카운터 i
결코 증가하지 않기 때문에JS 중첩 된 for 루프를 깨고
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.