求给定字符串的最长子字符串

以前经常听说这道题,奈何自己一直比较讨厌算法题这种东西,所以一直没看过解答啥的。没想到今天为了找工作我也要刷 LeetCode 了。
不费话了,下面就开始记录我的解题思路以及看过的官方和网友的答案吧!

我的答案

首先,我想到的就是从前向后遍历,使用两个变量分别记录最长子字符串 longest 和当前遍历得到的字符串 curr:

/**
 * Cerated by clearbug on 2018/2/22.
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.longestSubstring1("abcabcbb"));
        System.out.println(solution.longestSubstring1("bbbbb"));
        System.out.println(solution.longestSubstring1("pwwkew"));
        System.out.println(solution.longestSubstring1("c"));
        System.out.println(solution.longestSubstring1("dvdf"));
    }

    public int lengthOfLongestSubstring(String s) {
        return longestSubstring1(s).length();
    }

    /**
     * 最简单方法,从前向后遍历;
     *
     * @param s
     * @return
     */
    public String longestSubstring1(String s) {
        String longest = "", curr = "";
        for (int i = 0; i < s.length(); i++) {
            if (curr.contains(s.substring(i, i + 1))) {
                if (curr.length() > longest.length()) {
                    longest = curr;
                }
                curr = curr.substring(curr.indexOf(s.substring(i, i + 1)) + 1) + s.substring(i, i + 1);
            } else {
                curr += s.substring(i, i + 1);
            }
        }
        if (curr.length() > longest.length()) {
            longest = curr;
        }
        return longest;
    }
}

在基本思路的指导下还需完善下细节,然后提交,LeetCode 通过,也算是对得起列祖列宗了!

官方方法(一):简单粗暴

简单粗暴的方法就是使用 Java 中 Set 数据结构的特性,实现一个 allUnique 方法,然后再做双层遍历求解,代码如下:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j <= n; j++)
                if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
        return ans;
    }

    public boolean allUnique(String s, int start, int end) {
        Set<Character> set = new HashSet<>();
        for (int i = start; i < end; i++) {
            Character ch = s.charAt(i);
            if (set.contains(ch)) return false;
            set.add(ch);
        }
        return true;
    }
}

官方方法(二):滑动窗口

也是使用了 Java 中 Set 数据结构的特性求解,代码如下:

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;
    }
}

官方方法(三):滑动窗口优化版

使用 Java 中 HashMap 数据结构的特性做优化,代码如下:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

官方方法(四):终极优化

终极优化方法貌似就是使用数组作为直接存取表来优化查询速度了,代码如下:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        int[] index = new int[128]; // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            i = Math.max(index[s.charAt(j)], i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;
        }
        return ans;
    }
}

参考

  1. https://www.cnblogs.com/K-artorias/p/7665604.html
原文地址:https://www.cnblogs.com/optor/p/8460026.html