Longest Substring Without Repeating Characters

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 asubstring,"pwke" is a subsequence and not a substring.

Subscribe to see which companies asked this question

package temp;

/**
 * 
 * @author Mouse
 *
 */

public class Solution {
	public static int lengthOfLongestSubstring(String s) {
		if (s.length() == 0)
			return 0;
		if (s.length() == 1) {
			return 1;
		}
		// 下面处理的是至少含2个元素的字符串
		char[] c = s.toCharArray();
		int start = 0;
		int end = 0;
		int count = 0;
		// 下面的for是为了计算有多少个重复的元素并进行切分
		// count得到我才知道我new多少个空间去存放数据
		for (int i = end; i < c.length; i++) {
			for (int j = start; j < i; j++) {
				if (c[i] == c[j]) {
					start = j + 1;
					end = i - 1;
					count++;
				}

			}
		}
		// 恢复start和end的原状。我在这里只是不想重新申请新的变量,毕竟变量已经够用了
		start = 0;
		end = 0;
		int[] data = new int[count + 1];
		int mcount = count;
		count = 0;
		int ka = 0;
		int kb = 0;
		for (int i = end; i < c.length; i++) {
			for (int j = start; j < i; j++) {
				if (c[i] == c[j]) {
					// System.out.print("开始位置:" + start);
					ka = start;
					start = j + 1;
					end = i - 1;
					kb = end;
					// System.out.println("结束位置:" + end);
					data[count] = kb - ka + 1;
					count++;
				}

			}
			// 当end失效时即i到达s字符串最后一处,却没有找到与前面相同的元素
			if (i == s.length() - 1) {
				data[mcount] = i - start + 1;
			}
		}

		// 找最大的数
		if (count == 0) {
			return s.length();
		}
		int max = data[0];
		for (int i = 0; i < data.length; i++) {
			if (data[i] > max) {
				max = data[i];
			}

		}
		return max;
	}

	public static void main(String[] args) {
		String a = "c";
		int data = lengthOfLongestSubstring(a);
		System.out.println(data);
	}

}
以上代码我写得很清楚,我就不解释了哈

大家可以查看网上其它的做法:http://www.programcreek.com/2013/02/leetcode-longest-substring-without-repeating-characters-java/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值