1.英文題目java
Given a string, find the length of the longest substring without repeating characters.單元測試
Example 1:測試
Input: "abcabcbb" Output: 3 Explanation: The answer is , with the length of 3."abc"
Example 2:code
Input: "bbbbb" Output: 1 Explanation: The answer is , with the length of 1."b"
Example 3:leetcode
Input: "pwwkew" Output: 3 Explanation: The answer is , with the length of 3. Note that the answer must be a substring, is a subsequence and not a substring."wke""pwke"
2.解題string
package com.example.leetcode.medium; public class LengthOfLongestSubstring { public static int lengthOfLongestSubstring(String s) { if (s == null||s.length()==0) { return 0; } int max = 1; int medium = 1; for (int i = 0, j = 1,k=1; k < s.length(); ) { String a = s.substring(i, j); // System.out.println(a); String b = s.substring(k, k+1); // System.out.println(b); if (a.contains(b)) { i++; j=i+1; k =i+1; medium=1; } else { j++; k++; medium++; if (medium > max) { max = medium; } } } return max; } public static void main(String[] args) { System.out.println(lengthOfLongestSubstring("bbbb")); } }
單元測試it
package com.example.leetcode.medium; import org.junit.Assert; import org.junit.Test; public class LengthOfLongestSubstringTest { @Test public void should_return_When_string_is_abcabcbb() { Assert.assertEquals(3, LengthOfLongestSubstring.lengthOfLongestSubstring("abcabcbb")); } @Test public void should_return_When_string_is_dvdf() { Assert.assertEquals(3, LengthOfLongestSubstring.lengthOfLongestSubstring("dvdf")); } @Test public void should_return_When_string_is_au() { Assert.assertEquals(2, LengthOfLongestSubstring.lengthOfLongestSubstring("au")); } @Test public void should_return_When_string_is_null_string() { Assert.assertEquals(0, LengthOfLongestSubstring.lengthOfLongestSubstring("")); } @Test public void should_return_When_string_is_bbbb() { Assert.assertEquals(1, LengthOfLongestSubstring.lengthOfLongestSubstring("bbbbb")); } }