while循环退出条件
While loop exit condition
我想知道这个while循环是怎么退出的?因为 i 和 j 除了在 s.charAt(j++) 和 s.charAt(i++) 之外的任何地方都不会递增,这是在 j 或第 i 个位置查找 char。这也会增加 j 和 i 吗?在我看来,它应该只给你第 j++ 或 i++ 位置的字符代码,不是吗?
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
是的,使用 i++ 会增加 i 的值。
如果你想在下一个位置找到字符而不是 i,那么你可以简单地使用另一个变量并将 i+1 值存储在其中并使用它来访问字符。像这样:
z = i+1;
set.add(s.charAt(z));
使用post-increment 或 pre-increment 总是会改变 increment 变量的值,唯一不同的是它们何时增加 increment 变量的值。
我想知道这个while循环是怎么退出的?因为 i 和 j 除了在 s.charAt(j++) 和 s.charAt(i++) 之外的任何地方都不会递增,这是在 j 或第 i 个位置查找 char。这也会增加 j 和 i 吗?在我看来,它应该只给你第 j++ 或 i++ 位置的字符代码,不是吗?
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
是的,使用 i++ 会增加 i 的值。 如果你想在下一个位置找到字符而不是 i,那么你可以简单地使用另一个变量并将 i+1 值存储在其中并使用它来访问字符。像这样:
z = i+1;
set.add(s.charAt(z));
使用post-increment 或 pre-increment 总是会改变 increment 变量的值,唯一不同的是它们何时增加 increment 变量的值。