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.

解题思路一

由于题目给个tag为HashTable和Two Pointers

因此,我们可以定义一个HashTable,和两个Pointers,index1和index2,首先将String中元素不断添加进去,如果发现重复,则删除重复的元素和它之前的元素,它们在String中的位置分别用index1和index2进行标记,最后找到HashTable曾经的最大规模。这种思路的时间复杂度为O(n)代码如下

public class Solution {
static public int lengthOfLongestSubstring(String s) {
char[] char1 = s.toCharArray();
int longestLength = 0;
int startIndex = 0;
int lastIndex = 0;
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
for (int i = 0; i < char1.length; i++) {
if (hashMap.containsKey(char1[i])) {
lastIndex = hashMap.get(char1[i]);
if (longestLength < (i - startIndex)) {
longestLength = i - startIndex;
}
for (int j = startIndex; j <= lastIndex; j++) {
hashMap.remove(char1[j]);
}
startIndex = lastIndex+1;
}
hashMap.put(char1[i], i);
}
if(longestLength<char1.length-startIndex)
longestLength=char1.length-startIndex;
return longestLength;
}
}

但是,提交之后显示Time Limit Exceeded,看来时间复杂度还是太高,究其原因,在于中间有两个for循环,第二个for循环每进行一次删除都必须遍历一边,因此时间开销必然很大。

思路二:

其实每次添加过后,我们不一定要在HashMap中删除重复的元素,我们可以用一个指针记录需要删除元素的位置,如果出现重复元素,就把pointer置为重复元素最后一次出现的位置+1即可,判断之前最大的substring的长度和本次产生的substring长度的大小。之后将本元素添加进HashMap里面。当然,最后还需要判断下最后一次获得的子串的长度和之前长度的比较。

Java代码如下:

public class Solution {
static public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> hashMap = new HashMap<Character, Integer>();
int length = 0;
int pointer = 0;
for (int i = 0; i < s.length(); i++) {
if (hashMap.containsKey(s.charAt(i))&& hashMap.get(s.charAt(i)) >= pointer) {
length = Math.max(i-pointer, length);
pointer = hashMap.get(s.charAt(i)) + 1;
}
hashMap.put(s.charAt(i), i);
}
return Math.max(s.length() - pointer, length);
}
}

C++代码如下:

 #include<vector>
#include<unordered_map>
#include<string>
#include<algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> map;
int res = ;
int pointer = ;
int size = s.length();
for (int i = ; i < size; i++) {
unordered_map < char, int >::iterator iter;
iter = map.find(s[i]);
if (iter != map.end() && map[s[i]] >= pointer) {
res = max(res, i - pointer);
pointer = map[s[i]] + ;
}
if (iter != map.end())
map[s[i]] = i;
else
map.insert(unordered_map<char, int>::value_type(s[i], i));
}
return max(size - pointer,res);
}
};

解题思路三:

由于字母有限,使用STL中map开销太大直接使用数组实现map映射即可,C++实现如下:

 #include<string>
#include<algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = , point = ;
int prev[];
memset(prev, -, sizeof(prev));
for (int i = ; i < s.length(); i++) {
if (prev[s[i]] >= point)
point = prev[s[i]] + ;
prev[s[i]] = i;
res = max(res, i - point + );
}
return res;
}
};

【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters的更多相关文章

  1. 【JAVA、C++】LeetCode 005 Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  2. 【JAVA、C++】LeetCode 014 Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings. 解题思路: 老实遍历即可, ...

  3. LeetCode #003# Longest Substring Without Repeating Characters(js描述)

    索引 思路1:分治策略 思路2:Brute Force - O(n^3) 思路3:动态规划? O(n^2)版,错解之一:420 ms O(n^2)版,错解之二:388 ms O(n)版,思路转变: 1 ...

  4. [Leetcode]003. Longest Substring Without Repeating Characters

    https://leetcode.com/problems/longest-substring-without-repeating-characters/ public class Solution ...

  5. C++版- Leetcode 3. Longest Substring Without Repeating Characters解题报告

    Leetcode 3. Longest Substring Without Repeating Characters 提交网址: https://leetcode.com/problems/longe ...

  6. 【LeetCode】003. Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. Examples: Giv ...

  7. 【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters

    题目 Given a string, find the length of the longest substring without repeating characters. For exampl ...

  8. Java [leetcode 3] Longest Substring Without Repeating Characters

    问题描述: Given a string, find the length of the longest substring without repeating characters. For exa ...

  9. LeetCode之Longest Substring Without Repeating Characters

    [题目描述] Given a string, find the length of the longest substring without repeating characters. Exampl ...

随机推荐

  1. 查询条件Where

    1.字符串 $condition = 'name=\'Lily\' and age>10'; 2.数组 ['type' => 1, 'status' => 1] //生成 (type ...

  2. 10.Android之ProgressDialog进度对话框学习

    APP应用中经常会下载某些东西,这里面有涉及到进度对话框,今天来学习下. 首先,布局里放进两个按钮,点击一个显示条形进度条,另一个显示圆形进度条.代码如下: <?xml version=&quo ...

  3. BZOJ-2242 计算器 快速幂+拓展欧几里得+BSGS(数论三合一)

    污污污污 2242: [SDOI2011]计算器 Time Limit: 10 Sec Memory Limit: 512 MB Submit: 2312 Solved: 917 [Submit][S ...

  4. BZOJ-1901 Zju2112 Dynamic Rankings 函数式线段树 套 树状数组+离线处理

    1901: Zju2112 Dynamic Rankings Time Limit: 10 Sec Memory Limit: 128 MB Submit: 6058 Solved: 2521 [Su ...

  5. BZOJ-1045 糖果传递 数学+递推

    1045: [HAOI2008] 糖果传递 Time Limit: 10 Sec Memory Limit: 162 MB Submit: 2975 Solved: 1327 [Submit][Sta ...

  6. Opencv显示图片并监听鼠标坐标

    #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include & ...

  7. ubuntu设置开机启动图形应用程序,替换默认图形桌面

    直接将启动程序放在rc.local即可.但是如果自动启动的程序奔溃后,会返回到ubuntu的unity桌面系统. 我遇到的问题是程序还有调用 xset 去定时关闭屏幕.在桌面启动后调用没问题.如果rc ...

  8. 代码重构-3 用Tuple代替 out与ref

    返回单一值是良好的编程习惯 原代码: public LotteryViewModel ValidateLottery(LotteryBaseData baseData, int authTime, o ...

  9. jquery------.mouseover()和.mouseout()的高级效果使用

    index.jsp <div style="width:100%;height:40px;background-color:#aaa;position:absolute;"& ...

  10. 在微信中实现app软件中账号注册的功能实现

    利用写好的接口url地址访问 输入手机号,接收手机验证码 <span class="accept" >点击获取验证码</span> $(".acc ...