题解 | #牛牛的协作#
牛牛的协作
https://www.nowcoder.com/practice/ae483ed148b34e14bec1451b3317984d
知识点
字符串,双指针
解题思路
运用双指针和set,遍历s,当当前字符没有出现过在set中,右指针就向后移动一位,更新ans的最大值,set添加当前字符。
如果当前字符出现过在set中,set移除当前字符,左指针向右移动直到找到出现过的字符。当右指针到达s末尾结束返回ans。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ public int lengthOfLongestContinuousTasks (String s) { // write code here Set<Character> set = new HashSet<>(); int left = 0, right = 0, n = s.length(); int ans = 0; while(right != n){ char c = s.charAt(right); if(!set.contains(c)){ set.add(c); right ++; ans = Math.max(ans,right - left); } else{ while(s.charAt(left) != c){ set.remove(s.charAt(left++)); } set.remove(s.charAt(left++)); } } return ans; } }