LeeCode(3) Longest Substring Without Repeating Characters C语言

题目:
Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: “pwwkew”
Output: 3
Explanation: 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.

解法一:
基本思路:用双重循环,遍历字符串,用一个数组来记载是否遇到相同的字符。如果遇到,则记录字符串长度,并且开始下一次循环。

C语言代码:

 int lengthOfLongestSubstring(char * s){
        int i;
        int j;
        int len = 0;
        int res = 0;
        
        for(i=0;s[i]!='\0';i++)
        {
            int temp[256]={0};
            len =0;
            for(j=i;s[j]!='\0';j++)
            {
                
                int k = s[j];
                if(temp[k]!=0)
                {
                    break;
                }
                else
                {
                    temp[k]=1;
                    len++;
                }
                
            }
            
            if(len>res)
            {
                res=len;
            }
            
        }
        
        return res;
    }

执行效率:
执行时间较长,内存占用可还行?
解法一执行效率

解法二:
思路:只需要完整遍历一次字符串,在遍历的同时,设置2个指针,一个指向当前的字符(i),一个指向重复之后的下一个字符,表示新的不重复的字符串开始的位置(j)。用一个数组来检测是否有相同的字符。如果有相同的字符,则更新的数组以及 j 的指向,并记录当前最长长度。反之,则推进 i ,完成遍历。

C语言实现:

int lengthOfLongestSubstring(char * s){
    int i;
    int j;
    int len = 0;
    int res = 0;
    int temp[256]={0};
    
    
	for (i = 0, j = 0; s[i] != '\0';i++ )
	{

		int k = s[i];
		if (temp[k] != 0)
		{
			if (len > res)
			{
				res = len;
			}
			int m;
			while (s[j] != s[i])
			{
				m = s[j];
				temp[m] = 0;
				j++;
				len--;
			}
            j++;

		}
		else
		{
			temp[k] = 1;
			len++;
		}
	}
    
    if(len>res)
    {
        res=len;
    }
    return res;
}

效率:
时间效率显著提高,空间效率有所下降
解法二执行效率

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值