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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章