Java 杂谈Java

Longest Substring Without Repeat

2019-04-08  本文已影响0人  firststep

问题:

Given a string, find the length of the longest substring without repeating characters.
Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

分析:

  1. 首先拿到这道题首先想到的是一个队列结构,上面添加下面出。
  2. 如果碰到一样的就截取一样该元素以及该元素前面的所有元素。
  3. 定义两个字符串,表示当前current的和最长的longmax。所以比较到最后longmax中也就是最长的。
  4. 因为取得是最长的所以每一次当前的都要与最长的作比较.

答案:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        String current = "";
        String longmax = "";
        for (int i = 0; i<s.length(); i++) {
            if (current.length()>longmax.length()) {
                longmax = current;
            }
            char c = s.charAt(i);
            if (current.indexOf(c)>=0) {
                if (current.length()>1) {
                    current = current.substring(current.indexOf(c) + 1, current.length()) + Character.toString(c) ;
                } else {
                    current=Character.toString(c);
                }
            } else {
                current += c;
                if (longmax.length() < current.length())
                    longmax=current;
            }
        }
        return longmax.length();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读