ノー繰り返し文字LeetCode02-最長の部分文字列

タイトル説明

ここに画像を挿入説明

基本的な考え方

スライディングウィンドウ

  • 使用HashSet達成するために
  • 使用HashMap達成するために

Java実装

  • HashSetの
    public static int lengthOfLongestSubstring3(String s) {
        if(s == null || s.length() == 0) return  0;

        HashSet<Character> set = new HashSet<>();
        int res = 0;
        for(int i = 0, j = 0; i < s.length(); i ++ ) {
            if(set.contains(s.charAt(i))) {
                set.remove(s.charAt(j));
                j++;
                i--;
            } else {
                set.add(s.charAt(i));
                res = Math.max(res, i - j + 1);
            }
        }
        return res;
     }
  • HashMapの
    public static int lengthOfLongestSubstring2(String s) {
        if( s == null || s.length() == 0) return 0;
        HashSet<Character> set = new HashSet<>();
        int res = 0;
        for(int i = 0, j = 0; i < s.length(); i++) {
            if(set.contains(s.charAt(i))) {
                set.remove(s.charAt(j));
                j++;
            } else {
                set.add(s.charAt(i));
                res = Math.max(res, i - j + 1);
            }
        }
        return res;
    }

公開された32元の記事 ウォン称賛7 ビュー7578

おすすめ

転載: blog.csdn.net/Isaacddx/article/details/87881689