leecode algo3: Longest Substring Without Repeating Characters (Java)

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;
	}
}


你可能感兴趣的:(java,substring,longest)