LeetCode 3 Longest Substring Without Repeating Characters

public class Solution {public int lengthOfLongestSubstring(String s) {int left=0,Max=0;Map<Character,Integer> map = new HashMap<Character,Integer>();char[] chs = s.toCharArray();for(int i=0;i<chs.length;i++){if(map.containsKey(chs[i]) && map.get(chs[i])>=left){left = map.get(chs[i])+1;}map.put(chs[i],i);Max = Max>(i-left+1)?Max:(i-left+1);}return Max;}}C语言源代码:

#include<limits.h>#include<stdio.h>int lengthOfLongestSubstring(char* s) {int i,j,left=0,Max=0,hash[256];for(j=0;j<256;j++)hash[j]=INT_MAX;for(i=0;s[i];i++){if(hash[s[i]]!=INT_MAX && hash[s[i]]>=left)left=hash[s[i]]+1;hash[s[i]]=i;Max = Max>(i-left+1)?Max:(i-left+1);}return Max;}C++源代码:

class Solution {public:int lengthOfLongestSubstring(string s) {int Max=0,left=0;map<int,int> map;for(int i=0;i<s.size();i++){std::map<int,int>::iterator iter=map.find(s[i]);if(iter!=map.end() && iter->second >=left){left=iter->second+1;}map[s[i]]=i;Max = Max>(i-left+1)?Max:(i-left+1);}return Max;}};Python源代码:

class Solution:# @param {string} s# @return {integer}def lengthOfLongestSubstring(self, s):left=0Max=0hash={}for i in range(len(s)):ch = s[i]if hash.has_key(ch) and hash[ch]>=left:left=hash[ch]+1hash[ch]=iMax= Max if Max>i-left+1 else i-left+1return Max

,是我一生的快乐;失去你,是我一生的遗憾;没有你,无法感受心灵的震撼。

LeetCode 3 Longest Substring Without Repeating Characters

相关文章:

你感兴趣的文章:

标签云: