Leetcode -- Longest Substring Without Repeating Characters

来源:互联网 发布:java定时任务管理系统 编辑:程序博客网 时间:2024/06/06 04:04

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.

#define max(a,b) ((a)>(b)?(a):(b))
int lengthOfLongestSubstring(char* s) {
    int ans = 0, left = 0, len = strlen(s);
    int *assic = (int*)malloc(sizeof(int)*255);
    memset(assic, -1, sizeof(int)*255);
    for (int i = 0; i < len; i++) {
        if (assic[s[i]] >= left) left = assic[s[i]] + 1;
        assic[s[i]] = i;
        ans = max(ans, i - left + 1);
    }
    return ans;
}

需要注意的是max函数的定义最好加上这些括号,否则会因为运算符优先级等原因而计算错误,我也是填过这个坑才会这样说的。

另外一点就是memset函数中是sizeof(int)*255,因为Assic码有255个。

如果用malloc函数定义assic数组:

    int *assic = (int*)malloc(sizeof(int)*255);
    memset(assic, -1, sizeof(int)*255);  //255个int类型元素都初始化为-1

    memset(assic,-1,sizeof(assic)); //只有8/4=2个元素被初始化为-1,其他的值还是0

或者写成int assic[255]也可以,

    int assic[255];

    memset(assic,-1,sizeof(assic)); //255个-1,这就是数组和指针的区别

    memset(assic,-1,sizeof(int)*255); //255个-1

阅读全文
0 0
原创粉丝点击