LeetCode:Longest Substring Without Repeating Characters(java)
阿新 • • 發佈:2018-12-14
package LeetCode; /** * 題目: * 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 */ public class LengthOfLongestSubstring_03_1009 { public int LengthOfLongestSubstring(String s){ String result = "";//存放最長的字串 String temp = ""; int tail = 0; while (tail < s.length()) { if (!temp.contains(s.charAt(tail) + "")) { temp += s.charAt(tail); tail++; if (temp.length() > result.length()) { result = temp; } } else { temp = temp.substring(1); } } return result.length(); } public static void main(String[] args) { String s = "pwwkew"; LengthOfLongestSubstring_03_1009 test = new LengthOfLongestSubstring_03_1009(); int result = test.LengthOfLongestSubstring(s); System.out.println(result); } }