443. 压缩字符串-python-双指针

题目:

思路:

定义两个指针:read和write

read用来遍历chars,write是用来记录压缩后的字符的存入位置

代码:

复制代码
class Solution:
    def compress(self, chars: List[str]) -> int:
        #定义两个指针
        read=write=0
        n = len(chars)
        while read < n:
            cur = chars[read]
            count = 0
            while read < n and chars[read] == cur:
                read += 1
                count += 1
            #记录当前的字符
            chars[write]=cur
            write += 1
            if count > 1:
                # 把数字转成字符串,逐位写入
                for s in str(count):
                    chars[write]=s
                    write += 1
        return write
相关推荐
Charlie_lll2 小时前
力扣解题-移动零
后端·算法·leetcode
chaser&upper2 小时前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
weixin_499771552 小时前
C++中的组合模式
开发语言·c++·算法
iAkuya2 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
近津薪荼2 小时前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先
xiaoye-duck2 小时前
吃透 C++ STL list:从基础使用到特性对比,解锁链表容器高效用法
c++·算法·stl
松☆2 小时前
CANN与大模型推理:在边缘端高效运行7B参数语言模型的实践指南
人工智能·算法·语言模型
java干货3 小时前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序
开发语言·python·算法
皮皮哎哟3 小时前
数据结构:嵌入式常用排序与查找算法精讲
数据结构·算法·排序算法·二分查找·快速排序