欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

3、Longest Substring Without Repeating Characters,longestrepeating

来源: javaer 分享于  点击 19885 次 点评:168

3、Longest Substring Without Repeating Characters,longestrepeating


Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

思路

使用Hash Table 定义两个参数i、j 其中i用来表示Hash表的key 而j用来进行计算max 使用了
map.get() map.put() map.containsKey() Math.max()

代码

public class Solution {
    public int lengthOfLongestSubstring(String s) {
          if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();  //创建一个map的实例对象
        int max=0;
        for (int i = 0 , j = 0 ; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j, map.get(s.charAt(i))+1);  //如果字符串中有重复的字符则更新j的值
            } 
            map.put(s.charAt(i), i);
            max = Math.max(max,i-j+1);  //求出最大序列值
        }
        return max;
    }
}

相关文章

    暂无相关文章

用户点评