leetcode_longest substring without repeating characters
題目:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
我的答案:
int lengthOfLongestSubstring(string s) {int len;len = s.length();if(len<1)return 0;const char *p = s.c_str();set<char> Set;for (int i = 0; i<len; i++)Set.insert(*(p + i));int N = Set.size();if (N == 1)return N;while (N>1){for (int i = 0; i <= len - N; i++){set<char> Setn;for (int j = 0; j < N; j++)Setn.insert(*(p + i + j));if (Setn.size() == N)return N;Setn.clear();}N--;} }思路解析:
? ? ?我在做這個題目的時候,用到set,這是一種非常好用的數據結構,它里面不存放重復元素,我就是充分利用了這一點。具體是先將字符串轉換成字符數組,然后計算整個字符串中有N個不同的字符,然后以長度為N的窗口遍歷整個字符數組,若能找到一個位置,使得窗口中所有的字符都不相同,則輸出N,否則,將窗口長度減1,重復進行尋找,直到找到最長子字符串,程序退出。需要考慮一些特殊情況,比如輸入字符長度為0
總結
以上是生活随笔為你收集整理的leetcode_longest substring without repeating characters的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 時間比較,PHP用strtoti
- 下一篇: leetcode_median of t