2017-10-08 337 views
-1

我想知道while循環如何退出?因爲除了在s.charAt(j ++)和s.charAt(i ++)上尋找j或第i個位置上的char,i和j不會增加。這是否也會增加j和i?在我看來,它應該只給你在j ++或i ++的字符代碼,th位置不是這樣嗎?while循環退出條件

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的值

+0

'i ++'會改變存儲在'i'中的值。 –

+0

謝謝!這就是我相信它會做的。 –

回答

0

是。 如果你想在我的下一個位置找到角色,那麼你可以簡單地使用另一個變量並將i + 1值存儲在其中,並使用它來訪問角色。就像這樣:

z = i+1; 
set.add(s.charAt(z)); 

使用後增量或預增的變化總是增加變量的值,只有不同,當他們增加量超過變量的值。

+0

謝謝!現在我似乎已經明白了。 –

+0

如果答案對您有幫助,請接受。乾杯:) –