[LeetCode]3. Longest Substring Without Repeating Characters

发布时间:2020-07-11 00:00:43 作者:風子余
来源:网络 阅读:491

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.

题意:

给定一个字符串,找出最长的无重复的连续字串。就比如"pwwkew"的最长无重复连续字串是"wke"。


最易想到的方法就是字符串逐一开始查找,第一个字符串找到最长的字串,依次找出,取最大值即可。

由于有256个字符,故定义了个257长度的数组,足以存下所有字符。


思路

1)定义字符数组,并把256个的值都置为零。

2)逐个查找字符,如果未出现过,即把该下标对应的数组值置为一。若该下标值已经是一了,则返回,

3)重置全部数组元素元素为零,从下个下标开始继续查找不重复字串。

4)返回最大字串长度即可。


#define CHARACTERS 257

int lengthOfLongestSubstring(char* s) 
{
    if ( !s )
    {   
        return 0;
    }
    
    int character[CHARACTERS] = { 0 };
    int len = strlen(s);
    
    int cnt  = 0;
    int size = 0;
    int maxLen = 0;
    int index = 0;
    for ( index = 0; index < len; index++ )
    {
        size = 0;
        for ( cnt = 0; cnt < CHARACTERS; cnt++ )
        {
            character[cnt] = 0;
        }
        
        for ( cnt = index; cnt < len; cnt++ )
        {
            /* pwwkew */
            int value = *(s + cnt);
            if ( character[value] == 0 )
            {
                size += 1;
                character[value] = 1;
            }
            else
            {
                break;
            }
        }
        
        if ( size > maxLen )
        {
            maxLen = size;
        }
    }
    
    return maxLen;
}


推荐阅读:
  1. 记录在Windows上安装和使用Oracle数据库过程中的坑
  2. 定义数据模型&访问数据库

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

code leet ers

上一篇:request.getRequestDispatcher("login.html");页面乱码

下一篇: AWR报告参数:DB TIME和DB CPU

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》