3. Longest Substring Without Repeating Characters (Brute Force)

class Solution { public: bool unique(string s){ // given a string, check if all elements are unique in the string if (s.empty() || s.size() == 1) return true; for (size_t i = 0; i < s.size(); i++){ for (size_t j = i+1; j < s.size(); j++) if (s[i] == s[j]) return false; } return true; } int lengthOfLongestSubstring(string s) { if (s.empty() || s.size() == 1) return s.size(); vector<string> res; for (size_t i = 0; i < s.size(); i++){ for (size_t j = i; j < s.size(); j++){ string sub = s.substr(i, j - i + 1); // inclusive if (unique(sub)) res.push_back(sub); } } int longest = 0; for (string & r: res){ if (r.size() >= longest) longest = r.size(); } return longest; } };
Mistake 1: in the inner loop write "j++" as "i++" and cause segmentation fault.

Mistake 2: This solution is correct but will result in time limit exceed.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.