[LeetCode Java] 3 Longest Substring Without Repeating Characters

来源:互联网 发布:网络机顶盒app应用软件 编辑:程序博客网 时间:2024/06/10 11:29

题目地址:longest-substring-without-repeating-characters


import java.util.Arrays;/** *  * Given a string, find the length of the longest substring without repeating characters.  * For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.  * For "bbbbb" the longest substring is "b", with the length of 1. * */public class LongestSubstringWithoutRepeatingCharacters {//981 / 981 test cases passed.//Status: Accepted//Runtime: 245 ms//Submitted: 6 minutes agostatic int lengthOfLongestSubstring(String s) {int[] position = new int[256];Arrays.fill(position, -1);int maxLen = 0;int begin = 0;for (int i = 0; i < s.length(); i++) {int radix = s.charAt(i);if (position[radix] != -1) {if (begin < position[radix] + 1) begin = position[radix] + 1;}if (maxLen < i - begin + 1) maxLen++;position[radix] = i;}return maxLen;}public static void main(String[] args) {System.out.println(lengthOfLongestSubstring("abcabcc"));System.out.println(lengthOfLongestSubstring("abc"));System.out.println(lengthOfLongestSubstring("bbbbb"));System.out.println(lengthOfLongestSubstring("abba"));}}


0 0