【leetcode】3.Longest Substring Without Repeating Characters

来源:互联网 发布:杭州sql培训班 编辑:程序博客网 时间:2024/06/05 22:40
/*问题描述:Given a string, find the length of the longest substring without repeating characters.给定一个字符串,找出不重复最长子串的长度Examples:Given "abcabcbb", the answer is "abc", which the length is 3.Given "bbbbb", the answer is "b", with the length of 1.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.*/class Solution {    public int lengthOfLongestSubstring(String s) {int maxLength = 0;if ("".equals(s) || s == null) {return maxLength;}int maxLengthTmp = 0;int length = s.length();Set<String> set = new HashSet<String>();// 元素的不重复性int j = 0;for (int i = 0; i < length; i++) {if (set.add(s.substring(i, i + 1))) {maxLengthTmp++;if (maxLengthTmp > maxLength) {maxLength = maxLengthTmp;}} else {set = new HashSet<String>();// 重置maxLengthTmp = 0;j ++;i = j - 1;}}return maxLength;}}

leetcode最长字符串的消耗时间  183ms


阅读全文
1 0
原创粉丝点击