LeetCode03:无重复字符的最长子串
生活随笔
收集整理的這篇文章主要介紹了
LeetCode03:无重复字符的最长子串
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個字符串,請你找出其中不含有重復(fù)字符的?最長子串?的長度。
示例?1:
輸入: "abcabcbb" 輸出: 3 解釋: 因為無重復(fù)字符的最長子串是 "abc",所以其長度為 3。示例 2:
輸入: "bbbbb" 輸出: 1 解釋: 因為無重復(fù)字符的最長子串是 "b",所以其長度為 1。思路:這個比較簡單,判斷循環(huán)即可,判斷s[i]與s[j]是否相等,若不等,則判斷s[j]與s[i]之間的數(shù)即(s[i+1],s[i+2].....s[j-1]),若都不等,則繼續(xù)循環(huán),直到相等或者到字符串結(jié)尾終止。
#pragma once #include <string> #include <vector> #include <algorithm> using namespace std;/* 執(zhí)行用時 : 480 ms, 在Longest Substring Without Repeating Characters的C++提交中擊敗了2.12% 的用戶 內(nèi)存消耗 : 14.6 MB, 在Longest Substring Without Repeating Characters的C++提交中擊敗了0.93% 的用戶 */ int lengthOfLongestSubstring(string s) {int max = 0,temp2;for (int i = 0; i < s.size(); i++){int temp = 1;for (int j = i + 1; j < s.size(); j++){if (s[i] != s[j]){temp2 = 0;for (int t = j - 1; t > i; t--) {if (s[j] != s[t])temp2++;}if (temp2 == j - i - 1) {temp++;}elsebreak;}elsebreak;}if (temp > max)max = temp;}return max; }/* 優(yōu)解 執(zhí)行用時:12ms */int lengthOfLongestSubstring_Best(string s) {vector<int>v(128, 0);int t = 0; int ans = 0;for (int i = 0; i < s.length(); i++){t = max(t, v[s[i]]); //max函數(shù)在頭文件algorithm中ans = max(ans, i - t + 1);v[s[i]] = i + 1;}return ans; }
轉(zhuǎn)載于:https://www.cnblogs.com/cyhezt/p/10504356.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode03:无重复字符的最长子串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Load 和 DOMContentLoa
- 下一篇: python学习--练习题1、2、3、4