---
title: "LeetCode[字符串] - #3 Longest Substring Without Repeating Characters "
author: "Cwind"
date: "2015-07-20T16:57:59Z"
tags: []
categories: ["编程语言"]
slug: "leetcode-3-longest-substring-without-repeating-characters"
draft: false
lastmod: "2015-07-20T16:57:59Z"
id: 2228810
url: "https://cwind.iteye.com/blog/2228810"
---

原题链接：[#3 Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)

 

**要求：**

给定一个字符串，找到它没有重复字符的最长子串的长度。例如，"abcabcbb"的无重复字符最长子串为"abc"，其长度为3。对于由相同字符组成的字符串"bbbbb"，其最长子串为"b"，故返回长度为1。

 

**难度：**中等

 

**分析：**

遍历给定字符串，对于每一个字符c，若c不在临时字符串temp(初始化为空字符串)中，则将其加入temp；若temp包含c，则计算当前temp的长度并将其与当前记录的最大长度进行比较，以判断最大长度值是否需要更新。然后在temp中截取上一个c出现之后的子串，同时把c追加在后面，继续遍历过程即可。

 

**解决方案：**

```
public int lengthOfLongestSubstring(String s) {
        if(s.length()<=1){
            return s.length();
        }
        String temp = s.substring(0,1);
        int maxlength = 1;

        for(int i=1;i<s.length();i++){
            if(!temp.contains(String.valueOf(s.charAt(i)))){
                temp += s.charAt(i);
            }else{
                if(maxlength<temp.length()){
                    maxlength = temp.length();
                }
                temp = temp.substring(temp.indexOf(s.charAt(i))+1) + String.valueOf(s.charAt(i));
            }
        }
        if(maxlength < temp.length()){
            maxlength = temp.length();
        }
        return maxlength;
    }
```

[简单测试程序](https://github.com/cwind001/LeetCode/blob/master/LeetCodeJava/src/main/java/com/cwind/leetcode/string/LongestSubstring.java)