剑指offer48:无重复字符的最长子串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
在这里插入图片描述

  • 双指针法
public class Solution {
    
     
public static int lengthOfLongestSubstring(String s) {
    
     
   int n = s.length();
   Set<Character> set = new HashSet<>();
   int result = 0, i = 0, j = 0;
   while (i < n && j < n) {
    
     
   //charAt:返回指定位置处的字符 
   if (!set.contains(s.charAt(j))) {
    
     
   set.add(s.charAt(j));
    j++; 
   result = Math.max(result, j - i);
    } 
   else {
    
     
   set.remove(s.charAt(i));
    i++; } 
    }
    return result; 
    } 
  }

猜你喜欢

转载自blog.csdn.net/qq_43078445/article/details/107624790