/** * Created by kobe73er on 16/12/9. * <p> * Examples: * <p> * Given "abcabcbb", the answer is "abc", which the length is 3. * <p> * Given "bbbbb", the answer is "b", with the length of 1. * <p> * Given "pwwkew", 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. * <p> * Subscribe to see which companies asked this question */
public static int lengthOfLongestSubstring(String s) { if (s.equals("")) { return 0; } if (s.length() == 1) { return 1; } Set set = new HashSet(); int currentMax = 0; for (int m = 0; m < s.length(); m++) { int length = 0; for (int i = m; i < s.length(); i++) { if (set.contains(s.charAt(i))) { set.clear(); break; } else { set.add(s.charAt(i)); length++; } currentMax = length > currentMax ? length : currentMax; } } return currentMax; }
Longest string
最新推荐文章于 2018-01-04 11:43:26 发布