Leetcode代码学习周记——Longest Substring Without Repeating Characters

来源:互联网 发布:tensorflow 显卡要求 编辑:程序博客网 时间:2024/05/21 14:56

原题目链接:

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

题目描述:

给定一个字符串,求其最长的没有重复字符的子字符串长度。

实例:

给定 "abcabcbb", 答案为 "abc", 长度为3。

给定 "bbbbb",答案为 "b", 长度为1。

给定 "pwwkew",答案为 "wke", 长度为3。

注意答案必须是一个子字符串,"pwke" 是序列子集而不是子字符串。

本人对字符串处理的问题一直都很是头大,想了很久问题的处理方法,最后写出了如下代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int result = 0, left = 0;        int charaters[128];        memset(charaters, -1, sizeof charaters);        for (int i = 0; i < s.length(); i++) {            if (charaters[s[i]] >= left) {                left = charaters[s[i]] + 1;            }            charaters[s[i]] = i;            result = max(result, i - left + 1);        }        return result;    }};

result用于表示最长无重复字符的子字符串长度,left表示该子字符串的起点下标,

charaters[128]用于存储某个字符最后一次出现的位置。

通过遍历,不断比较原最长子字符串的长度和新的子字符串长度,最后得出结果。


运行时间击败了84.19%的提交程序,应该算是比较成功了。

阅读全文
0 0