[LeetCode]3. Longest Substring Without Repeating Characters

来源:互联网 发布:sdk软件开发工具包 编辑:程序博客网 时间:2024/04/29 23:43

题目:

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.

思路:

找最长子串,且子串内没有重复的字母,

比较简单。

class Solution {public:int lengthOfLongestSubstring(string s) {// Note: The Solution object is instantiated only once and is reused by each test case.bool a[256] = { false };for (int i = 0; i < 256; i++) a[i] = false;int temMax = 0,i=0,j;for ( j = 0; j < s.length(); j++) {if (!a[s[j]]) {a[s[j]] = true;}else {temMax=temMax > j - i ? temMax : j - i;while (s[i] != s[j]) {a[s[i]] = false;i++;}i++;}}temMax = temMax > s.length() - i ? temMax : s.length() - i;return temMax;}};












0 0
原创粉丝点击