[LeetCode] [C++] LeetCode 3 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.
LeetCode 3在线测试

问题描述


给定一个字符串s,计算该字符串s最长无重复字符子串长度。

示例说明:
给定字符串"abcabcbb",那么最长无重复子串是"abc",子串长度为3.

给定另一个字符串"bbbb",那么最长无重复子串是"b",子串长度为1.

给定字符串"pwwkew",那么最长无重复子串是"wke",子串长度为3.注意必须是原来字符串的子串,
"pwke"只是原来字符串的子序列,并非子串。

思路分析


  1. 采用C++内置数据结果set保存已经添加的字符,主要用到其count函数来判断下一个加入的字符是否已经存在
  2. 两层循环遍历真个字符串,外层循环负责定位substring的起始点,内层循环负责定位substring的终点

代码验证

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int ret = 0;

        do {
            if (s.size() <= 1) {
                ret = s.size();
                break;
            }

            set<char> setChars;
            for (int i = 0; i < s.size(); ++i) {
                for (int j = i; j < s.size(); ++j) {
                    if (setChars.count(s[j])) {
                        break;
                    } else {
                        setChars.insert(s[j]);
                    }
                }

                if (setChars.size() > ret) {
                    ret = setChars.size();
                }
                setChars.clear();
            }
        } while (false);

        return ret;
    }
};

运行后效果:
运行结果

总结注意


合理运用C++内置可用的数据结构set保存已经加入的字符char,可以快速判断新加入字符ch是否在当前子串已经存在

原创声明


作者:hgli_00
链接:http://www.cnblogs.com/lihuagang/p/leetcode_3.html
来源:博客园
著作权归作者所有,转载请联系作者获得授权。

posted @ 2017-04-21 15:18  hgli_00  阅读(829)  评论(0编辑  收藏  举报