您的位置:首页 > 其它

LeetCode OJ Longest Substring Without Repeating Characters

2015-03-22 17:33 447 查看
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            bool exist[256];
            int j;
            for (j = 0; j < 256; exist[j++] = false);
            for (j = i; j < s.size() && j < i + 256; j++) {
                if (exist[s[j]] == true) break;
                else exist[s[j]] = true;
            }
            ans = ans < j - i ? j - i : ans;
        }
        return ans;
    }
};


这个方法没有任何算法可言,448ms(当然其实leetcode上的时间统计好像不准- -)

以下这个比较好:100ms
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int maxDis = 0, newDis = 0;
        int latestPos[256];  // to record a character's latest position
        for (int i = 0; i < 256; latestPos[i++] = -1);  // -1 means no record
        for (int i = 0; i < s.size(); i++) {
            if (latestPos[s[i]] == -1 || latestPos[s[i]] < i - newDis)  // if no record or the latest position is too far for the new distance
                newDis++;
            else
                newDis = i - latestPos[s[i]];  // else the new distance is the distance between 2 same characters
            latestPos[s[i]] = i;  // renew the record
            if (newDis > maxDis) maxDis = newDis;
        }
        return maxDis;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: