最长不重复子串

/**

  • Longest Substring Without Repeating Characters
  • Given a string, find the length of the longest substring without repeating characters.
  • Example 1:
  • Input: “abcabcbb”
  • Output: 3
  • Explanation: The answer is “abc”, with the length of 3.
  • Example 2:
  • Input: “bbbbb”
  • Output: 1
  • Explanation: The answer is “b”, with the length of 1.
  • Example 3:
  • Input: “pwwkew”
  • Output: 3
  • Explanation: 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.
    */
    最差的方法就是蛮力法,各种遍历。
    leetCode推荐建立一个字符映射空间,将字符出现位置记录下来。比如ascii 的128位数组,index[128]。每一个位对应一个字符,数组的value记录字符最后出现的位置。
    所以当前最长子串就是两个字符位置之差。s[0] = a, s[3]=a,max = 3-0。

public class SubString {

public static void main(String[] args){
    System.out.println("start");
    String s = "abcabcbbccd";
    System.out.println(lengthOfLongestSubstring(s));
}

static 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++) {
        System.out.println(s.charAt(j));
        System.out.println(index[s.charAt(j)]);
        i = Math.max(index[s.charAt(j)], i);
        ans = Math.max(ans, j - i + 1);
        index[s.charAt(j)] = j + 1;
    }
    return ans;
}

}

你可能感兴趣的:(笔试题,算法笔试)