Skip to content

Commit

Permalink
added 109
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Feb 3, 2015
1 parent 00c8a99 commit c80bca1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
14 changes: 14 additions & 0 deletions 109. Longest Substring Without Repeating Characters/TEST.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"

TEST_CASE("Longest Substring Without Repeating Characters", "[lengthOfLongestSubstring]")
{
Solution s;
REQUIRE( s.lengthOfLongestSubstring("abcabcbb") == 3 );
REQUIRE( s.lengthOfLongestSubstring("bbbbb") == 1 );
REQUIRE( s.lengthOfLongestSubstring("a") == 1 );
REQUIRE( s.lengthOfLongestSubstring("au") == 2 );
REQUIRE( s.lengthOfLongestSubstring("bwt") == 3 );
REQUIRE( s.lengthOfLongestSubstring("abba") == 2 );
}
23 changes: 23 additions & 0 deletions 109. Longest Substring Without Repeating Characters/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#include <string>
using std::string;
#include <unordered_map>
using std::unordered_map;
#include <algorithm>
using std::max;

class Solution {
public:
int lengthOfLongestSubstring(string s) {
size_t ret=0, start=0;
unordered_map<char, size_t> cache = {{s.front(), 0}};
for (size_t last=1; last < s.size(); ++last) {
auto found = cache.find(s[last]);
if (found != cache.end() && found->second >= start) {
ret = max(ret, last - start);
start = found->second + 1;
}
cache[s[last]] = last;
}
return max(ret, s.size()-start);
}
};

0 comments on commit c80bca1

Please sign in to comment.