Longest Substring Without Repeating Characters

冷不防 2022-06-08 08:13 214阅读 0赞

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

思路:利用类似网络中的滑动窗口,

当新字符在窗口中没有出现时,将新字符加入窗口;

当新字符在窗口中出现过时,窗口的左边界移动到窗口中重复字符的右边。

  1. public class Solution {
  2. public int lengthOfLongestSubstring(String s){
  3. if(s==null||s.length()==0){
  4. return 0;
  5. }
  6. if(s.length()==1){
  7. return 1;
  8. }
  9. char [] chars=s.toCharArray();
  10. int left=0,right=0;
  11. int max=1;
  12. while (right + 1 < chars.length) {
  13. int t = hasReapeat(chars, left, right, chars[right + 1]);
  14. if (t == -1) {
  15. ++right;
  16. } else {
  17. left = t;
  18. }
  19. if (right - left + 1 > max) {
  20. max = right - left + 1;
  21. }
  22. }
  23. return max;
  24. }
  25. public static int hasReapeat(char [] chars,int left,int right,char c){
  26. int ans=-1;
  27. for(int i=left;i<=right;++i){
  28. if(c==chars[i]){
  29. return i+1;
  30. }
  31. }
  32. return ans;
  33. }
  34. }

发表评论

表情:
评论列表 (有 0 条评论,214人围观)

还没有评论,来说两句吧...

相关阅读