无重复字符的最长子串(中等)

一.题目描述

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
二.解法代码

被注释掉的是一个评论区的解法,它的是维护下标的思路,而不是维护字符串,是一种好解法,运行结果如下图

我的解法就是维护字符串,不大好,运行结果就不贴了。因为一开始没想太多,还需要好好学习优良的思路。(静态方法好像要改成非静态,可能提交会出问题)

package test;

import java.util.ArrayList;
import java.util.List;

public class leetcodetest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s = "asdasdfffasdk";
		int ttt = lengthOfLongestSubstring(s);
		System.out.println(ttt);
	}

	public static int lengthOfLongestSubstring(String s) {
		char[] string = s.toCharArray();// 把传入的字符串转化为char数组
		List<Character> target = new ArrayList();// 设置目标字符集合
		Character a = null;// 保存每次取到的单个字符
		int result = 0;// 用来保存返回结果
		int beginindex = 0;// 设置取字符的下标
		int length = s.length();// 记录传入字符串的长度
		if (s.equals(""))
			return 0;
		while (beginindex < length) {

			a = string[beginindex];// 从传入字符串中取下标值元素

			if (search(a, target)) {// 如果目标集中存在该字符
				if (result < target.size())
					result = target.size();// 把本次结果保留

				target.clear(); // 把目标集合清空
				beginindex++;
			} else {// 如果目标集中不存在

				for (int i = beginindex; i < length; i++) {
					a = string[i];
					if (!search(a, target)) {
						target.add(a);
					} else
						break;

				}

				if (result < target.size())
					result = target.size();// 把本次结果保留

			}

		}
		return result;
//		 int maxLength = 0;
//		    char[] chars = s.toCharArray();
//		    int leftIndex = 0;
//		    for (int j = 0; j < chars.length; j++) {
//		      for (int innerIndex = leftIndex; innerIndex < j; innerIndex++) {
//		        if (chars[innerIndex] == chars[j]) {
//		          maxLength = Math.max(maxLength, j - leftIndex);
//		          leftIndex = innerIndex + 1;
//		          break;
//		        }
//		      }
//		    }
//		    return Math.max(chars.length - leftIndex, maxLength);
	}

	// 查找是否目标字符集中存在每次取到的单个字符
	public static boolean search(Character c, List<Character> target) {
		Boolean result = null;
		result = target.contains(c);
		return result;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值