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. POJ1125 Stockbroker Grapevine

    Description Stockbrokers are known to overreact to rumours. You have been contracted to develop a me ...

  2. Windows Server 2008系统如何取消登录时要按Ctrl+Alt+Delete组合键

    1.点桌面任务栏的“开始-->运行”在弹出的窗口中输入gpedit.msc . 2.输入gpedit.msc后,点击确定即打开了组策略编辑器.在组策略编辑器的左框内依次序展开(点前面的“+”号) ...

  3. git使用记录

    唔,git有本地版本管理功能,所以,这个完全是可以拿来自己做版本管理的.所以有必要学习一下,另外,在oschina上开了个账户,用来管理自己一些代码,也是增加自己学习git的动力. 1. 使用clon ...

  4. [IOS UIalert模版]

    1.alertview创建 UIAlertView *alert; alert = [[UIAlertView alloc] initWithTitle:@"提示" message ...

  5. map 几种遍历方法

    public static void main(String[] args) { Map<String, String> map = new HashMap<String, Stri ...

  6. MyEclipse------各种问题解决方法

    1.汉化后如何变为英文版:找到myeclipse.ini文件,改为:language=enlanguage=zh为中文 2.解决版本不匹配问题:http://blog.sina.com.cn/s/bl ...

  7. c/s架构nginx+php-fpm通信原理

        FastCGI是一个运用于Http Server和动态脚本语言间通信的接口,多数流行的Http Server都支持FastCGI,包括Apache.Nginx和lighttpd等.同时,Fas ...

  8. 利用memcached构建高性能的Web应用程序(转载)

    面临的问题 对于高并发高访问的Web应用程序来说,数据库存取瓶颈一直是个令人头疼的问题.特别当你的程序架构还是建立在单数据库模式,而一个数据池连接数峰 值已经达到500的时候,那你的程序运行离崩溃的边 ...

  9. C# 根据IP地址获取城市

    using System; using System.IO; using System.Net; using System.Text; using System.Web.Script.Serializ ...

  10. POJ 2503 Babelfish

    Babelfish Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 28766 Accepted: 12407 Descripti ...