【100Days of 100 line Code】6 day

本文详细介绍了如何通过遍历字符串并使用新列表和新字符串来解决LeetCode #3题,寻找无重复字符的最长子串。包括更新对比字符串、查找重复字符以及对新列表进行排序等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天很低产,做了一道题。

只想说一句,去你妈的。

最后一例没有过,时间超出限制。

按理说,时间复杂度也就应该是O(n),但是没过。好吧,不说这些了。

LeetCode #3 无重复字符的最长子串

创建新列表new_list,储存每个字符能组成的最长字符串的长度。

创建新字符串new_str,作为对比字符串。

创建断点seat

对比字符串长度lenght可以后面写出 new_list.append(len(new_str)),我这里就不改了。便于可读。

算法部分。

遍历一次字符串s,判断是否在对比字符串当中。

不在的话,更新对比的字符串(新的对比字符串即为断点之后到s[i]),并将长度储存到new_list[i](表示s[i]可以组成无重复最长子串的长度)

在的话,即对比字符串与即将加入的s[i]字符有重复。

遍历s[i]之前的字符串,找的最后一个和s[i]重复的字符。

更新seat,更新对比字符串,并将长度储存到new_list[i]之中。

最后在对new_list进行排序,返回最大值即可。

重复的代码有点多,为了简介可以创建一个新的函数更新数据。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == '':
            return 0
        new_list = []
        new_str = ''
        length = 0
        seat = 0for i in range(len(s)):
            if s[i] not in new_str:   
                new_str = s[seat:i+1]
                length = len(new_str)
                new_list.append(length)else :
                for j in range(i):
                    if s[i] == s[j]:
                        seat = j + 1        
                new_str = s[seat:i+1]
                length = len(new_str)
                new_list.append(length)
        new_list.sort()
        return new_list[-1]

 

转载于:https://www.cnblogs.com/mygzhh/p/9315793.html

/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention »ùÓÚSTM32µÄÍòÄêÀú Ч¹ûÑÝʾÊÓÆµÁ´½Ó£ºhttps://www.bilibili.com/video/BV11w4m1a74J/ ÓÎϷЧ¹û¿ÉÒÔ ¹Ø×¢ ΢ÐŹ«Öںš¢BÕ¾¡¢¶¶ÒôºÍ¿ìÊÖµÈÆ½Ì¨£¨Õ˺ÅÃû³Æ£ºJLµ¥Æ¬»ú£©£¬ÓÐÂ¼ÖÆµÄÊÓÆµµÄЧ¹û¡£ Ò²·ÖÏíÁËÆäËûºÃÍæÓÐȤµÄ´úÂ룬¶¼¿ÉÒÔȥ΢ÐŹ«ÖÚºÅÏÂÔØ¡£¸ÐÐËȤµÄ¿ÉÒÔ¿´Ï¡£ ²ÄÁÏ£º STM32F103C8T6×îСϵͳ°å SSD1306 OLED128*64ÏÔʾÆÁ 6¸ö°´¼ü IO½ÓÏß˵Ã÷£º Ïòϰ´¼ü£ºPA4 ÏòÓÒ°´¼ü£ºPA5 ÏòÉϰ´¼ü£ºPB11 Ïò×ó°´¼ü£ºPB10 F1°´¼ü£ºPA6 OLED SCK£ºPA11 OLED SDA£ºPA12 * Copyright (c) 2024 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "OLED.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ #define LEFT_BUTTON 1 #define RIGHT_BUTTON 2 #define UP_BUTTON 3 #define DOWN_BUTTON 4 #define A_BUTTON 5 #define B_BUTTON 6 /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ uint32_t yr = 2024; uint8_t mo = 7; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ unsigned char isLeapYear(uint32_t yr) { if (yr % 100) return (yr % 400) == 0; else return (yr % 4) == 0; } uint8_t getDaysOfMonth(uint32_t yr, uint8_t mo) { return (mo == 2) ? (28 + isLeapYear(yr)) : 31 - (mo - 1) % 7 % 2; } uint8_t getDayOfWeek(uint32_t yr, uint8_t mo, uint8_t d) { return (d += mo < 3 ? yr-- : yr - 2, 23 * mo / 9 + d + 4 + yr / 4 - yr / 100 + yr / 400) % 7; } int get_key_input() { if(HAL_GPIO_ReadPin(left_key_GPIO_Port, left_key_Pin)==0){ HAL_Delay(100); if(HAL_GPIO_ReadPin(left_key_GPIO_Port, left_key_Pin)==0) return LEFT_BUTTON; } if(HAL_GPIO_ReadPin(right_key_GPIO_Port, right_key_Pin)==0) { HAL_Delay(100); if(HAL_GPIO_ReadPin(right_key_GPIO_Port, right_key_Pin)==0) return RIGHT_BUTTON; } if(HAL_GPIO_ReadPin(up_key_GPIO_Port, up_key_Pin)==0) { HAL_Delay(100); if(HAL_GPIO_ReadPin(up_key_GPIO_Port, up_key_Pin)==0) return UP_BUTTON; } if(HAL_GPIO_ReadPin(down_key_GPIO_Port, down_key_Pin)==0) { HAL_Delay(100); if(HAL_GPIO_ReadPin(down_key_GPIO_Port, down_key_Pin)==0) return DOWN_BUTTON; } if(HAL_GPIO_ReadPin(f1_key_GPIO_Port, f1_key_Pin)==0) { HAL_Delay(100); if(HAL_GPIO_ReadPin(f1_key_GPIO_Port, f1_key_Pin)==0) return A_BUTTON; } if(HAL_GPIO_ReadPin(f2_key_GPIO_Port, f2_key_Pin)==0) { HAL_Delay(100); if(HAL_GPIO_ReadPin(f2_key_GPIO_Port, f2_key_Pin)==0) return B_BUTTON; } return 0; } void update() { switch (get_key_input()) { case LEFT_BUTTON: if (--yr < 1970) yr = 1970; break; case RIGHT_BUTTON: if (++yr > 2199) yr = 2199; break; case UP_BUTTON: if (++mo > 12) { if (++yr > 2199) { yr = 2199; mo = 12; } else { mo = 1; } } break; case DOWN_BUTTON: if (--mo < 1) { if (--yr < 1970) { yr = 1970; mo = 1; } else { mo = 12; } } break; case A_BUTTON: yr = 2024; mo = 7; break; case B_BUTTON: break; } } void draw() { uint8_t days = getDaysOfMonth(yr, mo); uint8_t day = getDayOfWeek(yr, mo, 1); OLED_ShowNum(40, 0, yr, 4, OLED_6X8); OLED_ShowNum(70, 0, mo, 2, OLED_6X8); OLED_ShowString(4, 8, "SU MO TU WE TH FR SA", OLED_6X8); uint8_t x = day; uint8_t y = 0; for (uint8_t i = 1; i <= days; ++i) { if (i < 10) { OLED_ShowNum(x * 18 + 4 + 6, y * 8 + 16, i, 1, OLED_6X8); } else { OLED_ShowNum(x * 18 + 4, y * 8 + 16, i, 2, OLED_6X8); } if (++x == 7) { x = 0; ++y; } } } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); /* USER CODE BEGIN 2 */ OLED_Init(); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while(get_key_input()==0); while (1) { OLED_Clear(); update(); draw(); OLED_Update(); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* USER CODE BEGIN MX_GPIO_Init_1 */ /* USER CODE END MX_GPIO_Init_1 */ /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOA, scl_Pin|sda_Pin, GPIO_PIN_SET); /*Configure GPIO pins : down_key_Pin right_key_Pin f1_key_Pin f2_key_Pin */ GPIO_InitStruct.Pin = down_key_Pin|right_key_Pin|f1_key_Pin|f2_key_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pins : left_key_Pin up_key_Pin */ GPIO_InitStruct.Pin = left_key_Pin|up_key_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : scl_Pin sda_Pin */ GPIO_InitStruct.Pin = scl_Pin|sda_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USER CODE BEGIN MX_GPIO_Init_2 */ /* USER CODE END MX_GPIO_Init_2 */ } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ 学习代码
06-18
from jqdata import * def initialize(context): set_params(context) # 设置参数 set_backtest() # 设置回测条件 def set_params(context): context.stock_pool = [ {'code': '399673.XSHE', 'name': '创业板50'}, {'code': '000688.XSHG', 'name': '科创50'}, {'code': '399303.XSHE', 'name': '国证2000'} ] context.bond_code = '000012.XSHG' # 国债指数 context.cy_index = '399006.XSHE' # 创业板指 context.ma_days = 20 # 均线周期 context.rank_days = 20 # 排名计算周期 context.sell_ma = 10 # 卖出均线周期 def set_backtest(): set_benchmark('399673.XSHE') set_option('use_real_price', True) set_order_cost(OrderCost( open_tax=0, close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5 ), type='stock') # 新增移动平均计算函数 def get_ma(security, n_days, data): """计算N日移动平均线""" hist = attribute_history(security, n_days, fields='close') return hist['close'].mean() def handle_data(context, data): if not is_trading_day(context): return check_sell_condition(context, data) check_buy_condition(context, data) def is_trading_day(context): return not (context.current_dt.hour == 15 and context.current_dt.minute == 0) def check_sell_condition(context, data): for stock in context.portfolio.positions: if stock.code == context.bond_code: continue current_price = data[stock.code].close ma10 = get_ma(stock.code, context.sell_ma, data) if current_price < ma10: clear_position(context, stock.code) log.info(f"触发平仓条件:{stock.code} 价格跌破10日均线") def check_buy_condition(context, data): if len(context.portfolio.positions) > 0: return # 大盘择时判断 cy_price = data[context.cy_index].close cy_ma20 = get_ma(context.cy_index, context.ma_days, data) if cy_price <= cy_ma20: return # 计算标的排名 ranked_stocks = [] for stock in context.stock_pool: current_price = data[stock['code']].close ma20 = get_ma(stock['code'], context.rank_days, data) ratio = (current_price - ma20) / ma20 ranked_stocks.append((stock, ratio)) # 按涨幅排序 ranked_stocks.sort(key=lambda x: x[1], reverse=True) target_stock = ranked_stocks[0][0] # 修正此行语法错误 current_price = data[target_stock['code']].close # 获取标的当前价格 cy_ma20 = get_ma(context.cy_index, context.ma_days, data) # 重新获取创业板指MA20 # 最终开仓判断 if current_price > cy_ma20: order_value(target_stock['code'], context.portfolio.available_cash) log.info(f"开仓买入:{target_stock['name']}") def clear_position(context, code): """清空指定标的持仓""" order_target(code, 0) File "/tmp/strategy/user_code.py", line 38, in handle_data check_sell_condition(context, data) File "/tmp/strategy/user_code.py", line 46, in check_sell_condition if stock.code == context.bond_code: continue AttributeError: 'str' object has no attribute 'code' 针对这两个问题 进行改正 并给出新代码
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值