leecode algo3: Longest Substring Without Repeating Characters (Java)

来源:互联网 发布:vb教程 编辑:程序博客网 时间:2024/04/28 09:29

leetcode algo3:Longest Substring Without Repeating Characters

题目: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.

实现思想:见我的另一篇博客: http://blog.csdn.net/liyuming0000/article/details/46925509

具体实现如下(leetcode 提交通过, Run Time:5ms):

package algo3;public class Solution {public static void main(String[] args) {Solution s = new Solution();String str = "jhhjnsfudufbdfyscfbsdjjS";System.out.println(s.lengthOfLongestSubstring(str));}public int lengthOfLongestSubstring(String s) {/*if(s == null)return 0;char [] sCharArr = s.toCharArray();HashMap<Character, Integer> charsIndex = new HashMap<Character, Integer>();int startIndex = -1, maxLen = 0;for(int index = 0; index < sCharArr.length; index++) {if(charsIndex.containsKey(sCharArr[index])) {int oriIndex = charsIndex.get(sCharArr[index]);if(oriIndex > startIndex){startIndex = oriIndex;}}if(index - startIndex > maxLen) {maxLen = index - startIndex;}charsIndex.put(sCharArr[index], index);}return maxLen; */if(s == null)return 0;char [] sCharArr = s.toCharArray();int [] charsIndex = new int[256];for(int index = 0; index < 256; index++)charsIndex[index] = -1;int startIndex = -1, maxLen = 0;for(int index = 0; index < sCharArr.length; index++) {if(charsIndex[sCharArr[index]] > startIndex)startIndex = charsIndex[sCharArr[index]];if(index - startIndex > maxLen) {maxLen = index - startIndex;}charsIndex[sCharArr[index]] = index;}return maxLen;}}


0 0
原创粉丝点击