zoukankan      html  css  js  c++  java
  • LeetCode03:无重复字符的最长子串

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    示例 1:

    输入: "abcabcbb"
    输出: 3 
    解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

    示例 2:

    输入: "bbbbb"
    输出: 1
    解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。


    思路:这个比较简单,判断循环即可,判断s[i]与s[j]是否相等,若不等,则判断s[j]与s[i]之间的数即(s[i+1],s[i+2].....s[j-1]),若都不等,则继续循环,直到相等或者到字符串结尾终止。

    #pragma once
    #include <string>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    /*
    执行用时 : 480 ms, 在Longest Substring Without Repeating Characters的C++提交中击败了2.12% 的用户 
    内存消耗 : 14.6 MB, 在Longest Substring Without Repeating Characters的C++提交中击败了0.93% 的用户
    */
    int lengthOfLongestSubstring(string s) {
    	int max = 0,temp2;
    	for (int i = 0; i < s.size(); i++)
    	{
    		int temp = 1;
    		for (int j = i + 1; j < s.size(); j++)
    		{
    			if (s[i] != s[j])
    			{
    				temp2 = 0;
    				for (int t = j - 1; t > i; t--) 
    				{
    					if (s[j] != s[t])
    						temp2++;
    				}
    				if (temp2 == j - i - 1) {
    					temp++;
    				}
    				else
    					break;
    			}
    			else
    				break;
    		}
    		if (temp > max)
    			max = temp;
    	}
    	return max;
    }
    
    
    /*
    优解
    执行用时:12ms
    */
    
    int lengthOfLongestSubstring_Best(string s)
    {
    	vector<int>v(128, 0);
    	int t = 0; int ans = 0;
    	for (int i = 0; i < s.length(); i++)
    	{
    		t = max(t, v[s[i]]);		//max函数在头文件algorithm中
    		ans = max(ans, i - t + 1);
    		v[s[i]] = i + 1;
    	}
    	return ans;
    }
    

      

  • 相关阅读:
    crontab 实际的应用
    php 求素数的二种方法
    linux svn配置hooks
    php执行超时(nginx,linux环境)
    php使用strpos,strstr,strchr注意啦,若是数字查找则会当成ASCII码处理
    php 处理大文件方法 SplFileObject
    高德地图定位
    jquery 实现鼠标点击div盒子移动功能
    centos 安装php缓存 apc或zend-opcode
    phpQuery用法总结
  • 原文地址:https://www.cnblogs.com/cyhezt/p/10504356.html
Copyright © 2011-2022 走看看