LeetCode——3. 无重复字符的最长子串

题目描述:

LeetCode——3. 无重复字符的最长子串

 

注:本分类博客中的所有代码可以直接拷贝到eclipise

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 
 *
 * @版权 : Copyright (c) 2017-2018 *********公司技术开发部
 * @author: gaozhenchao
 * @E-mail: [email protected]
 * @版本: 1.0
 * @创建日期: 2019年1月23日 下午5:48:52
 * @ClassName Solution
 * @类描述-Description: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
 * @修改记录:
 * @版本: 1.0
 */
class Solution {
	public int lengthOfLongestSubstring(String s) {

		// 如果空串返回0
		if (s.equals("")) {
			return 0;
		}
		String r = "";
		// 计算每段的长度
		int count = 0;
		// 存储每段的长度
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		char[] charArray = s.toCharArray();
		for (int i = 0; i < charArray.length; i++) {
			// 判断r里面是否有charArray[i]
			if (r.indexOf(charArray[i] + "") >= 0) {
				// 存储上一段count值
				arrayList.add(count);
				// 判断 相邻字节相同的情况 例如 bbbb pwwkew->wkew
				if (i >= 1 && charArray[i] == charArray[i - 1]) {
					count = 0;
					r = "";
				} else {
					int j;
					j = i;
					// 防止string的substring索引越界
					if (j >= r.length()) {
						j = r.length();
					}
					// 截断匹配的第一个字节 例如 dvdf 把dv截成v
					r = r.substring(r.indexOf(charArray[i] + "") + 1, j);
					// 存储截断之后字符串长度
					count = r.length();
				}
				// 把不同的字节加入字符串
				r += charArray[i];
				// 每加一个计数器加一
				count++;
				continue;
			} else {
				// 字符串中没有匹配相同的字节,就加入
				r += charArray[i];
				count++;
			}
			// 把最后一次的count加入到集合中
			arrayList.add(count);
		}
		// 返回集合中最大值
		return Collections.max(arrayList);

	}
}

public class MainClass {

	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = in.readLine()) != null) {

			int ret = new Solution().lengthOfLongestSubstring(line);

			String out = String.valueOf(ret);

			System.out.println(out);
		}
	}
}