栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode

 我的题解

class Solution:
 def minOperations(self, s: str) - int:
 return min(self.startWith1(s),self.startWith0(s))
 def startWith1(self,s:str) - int:
 i,cnt 0,0
 key 0
 maps {
 1: 1 ,
 0: 0 
 while i len(s):
 key key^1
 if s[i] maps[key]:
 pass
 else:
 cnt 1
 return cnt
 def startWith0(self,s:str) - int:
 i,cnt 0,0
 key 1
 maps {
 1: 1 ,
 0: 0 
 while i len(s):
 key key^1
 if s[i] maps[key]:
 pass
 else:
 cnt 1
 return cnt

我的思路

1 一个既定的字符串 要么0开头要么1开头 这两种情况下要翻转操作是不同的

2 我们要求这两种情况的解 并且取它们的最小值

其余的优秀的题解

class Solution:
 def minOperations(self, s: str) - int:
 n len(s)
 cnt, cnt2 0, 0
 for i in range(n):
 if s[i] ! str(i % 2):
 cnt 1
 else:
 cnt2 1
 return min(cnt, cnt2)

一次循环下计算两种情况的cnt

class Solution:
 def minOperations(self, s: str) - int:
 x s[::2].count( 1 ) s[1::2].count( 0 )
 return min(x, len(s) - x)

s[::2].count( 1 )  偶数位有多少个1 

s[1::2].count( 0 )奇数位有多少个0

相加 这是表示1开头的cnt

len(s)-x 正好表示相反的情况 即是 0开头的cnt

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/267596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号