作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/reorganize-string/description/

题目描述:

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  1. S will consist of lowercase letters and have length in range [1, 500].

题目大意

输入是一个字符串,如果这个字符串重新排列之后能组成一个新字符串使得这个字符串相邻的字符都不相同,那么返回这个新字符串;如果做不到,就返回空字符串。

解题方法

这个题我知道要用Counter,而且也知道要做多次操作,可是我想的是递归,没做出来。。看了书影博客,才做出来的。

方法是:

统计这个字符串每个字符的出现频率,在组成新字符串时,在满足和上一个字符不相同的情况下,优先使用最流行的字符串。每用一个字符都对counter进行更新,直至循环结束。注意如果次数为0要删除,否则counter不会为空。

class Solution(object):
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
counter = collections.Counter(S)
ans = "#"
while counter:
stop = True
for item, times in counter.most_common():
if ans[-1] != item:
ans += item
counter[item] -= 1
if not counter[item]:
del counter[item]
stop = False
break
if stop: break
return ans[1:] if len(ans) == len(S) + 1 else ""

其实这个题和358. Rearrange String k Distance Apart题目一模一样的,都是使用小根堆+优先使用出现次数多的字符方法进行模拟。

需要留意的地方是出现的次数是正的,python的堆是小根堆,所以进堆的时候把次数取了符号,这样的话,中间对次数-1的步骤实际上使用的是+1。另外,已经使用过了的字符这轮就不会再取了,所以使用temp临时保存一下。

代码也基本相同,如下:

class Solution(object):
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
_len = len(S)
count = collections.Counter(S)
que = [(-v, c) for c, v in count.items()]
heapq.heapify(que)
res = ""
while _len:
cnt = min(_len, 2)
temp = list()
for i in range(cnt):
if not que:
return ""
v, c = heapq.heappop(que)
res += c
if v + 1 != 0:
temp.append((v + 1, c))
_len -= 1
for x in temp:
heapq.heappush(que, x)
return res

日期

2018 年 6 月 13 日 ———— 腾讯赛圆满结束!两个月修得正果哈哈~~
2018 年 10 月 14 日 —— 周赛做出来3个题,开心

【LeetCode】767. Reorganize String 解题报告(Python)的更多相关文章

  1. [LeetCode] 767. Reorganize String 重构字符串

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  2. LeetCode - 767. Reorganize String

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  3. 【LeetCode】481. Magical String 解题报告(Python)

    [LeetCode]481. Magical String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http:/ ...

  4. 【LeetCode】833. Find And Replace in String 解题报告(Python)

    [LeetCode]833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu ...

  5. 【LeetCode】678. Valid Parenthesis String 解题报告(Python)

    [LeetCode]678. Valid Parenthesis String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人 ...

  6. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  7. [leetcode]Weekly Contest 68 (767. Reorganize String&&769. Max Chunks To Make Sorted&&768. Max Chunks To Make Sorted II)

    766. Toeplitz Matrix 第一题不说,贼麻瓜,好久没以比赛的状态写题,这个题浪费了快40分钟,我真是...... 767. Reorganize String 就是给你一个字符串,能不 ...

  8. 767. Reorganize String - LeetCode

    Question 767. Reorganize String Solution 题目大意: 给一个字符串,将字符按如下规则排序,相邻两个字符一同,如果相同返回空串否则返回排序后的串. 思路: 首先找 ...

  9. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

随机推荐

  1. bwa比对软件的使用以及其结果文件(sam)格式说明

    一.bwa比对软件的使用 1.对参考基因组构建索引 bwa index -a bwtsw hg19.fa   #  -a 参数:is[默认] or bwtsw,即bwa构建索引的两种算法,两种算法都是 ...

  2. 添加页面、页面交互、动态添加页面tab

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ViewDictTosPr ...

  3. c#Gridview添加颜色

    e.Row.Cells[1].ForeColor = System.Drawing.Color.Blue;

  4. A Child's History of England.36

    CHAPTER 11 ENGLAND UNDER MATILDA AND STEPHEN The King was no sooner dead than all the plans and sche ...

  5. day14搭建博客系统项目

    day14搭建博客系统项目 1.下载代码包 [root@web02 opt]# git clone https://gitee.com/lylinux/DjangoBlog.git 2.使用pid安装 ...

  6. 静态库动态库的编译、链接, binutils工具集, 代码段\数据段\bss段解释

    #1. 如何使用静态库 制作静态库 (1)gcc *.c -c -I../include得到o文件 (2) ar rcs libMyTest.a *.o 将所有.o文件打包为静态库,r将文件插入静态库 ...

  7. C++字节对齐(对象大小)

    内部数据成员对齐参考这篇 https://www.cnblogs.com/area-h-p/p/10316128.html 这里只强调C++字节对齐特点 ①静态数据成员属于类域,在对象中不占大小 ②若 ...

  8. linux添加用户、权限

    # useradd –d /usr/sam -m sam 此命令创建了一个用户sam,其中-d和-m选项用来为登录名sam产生一个主目录/usr/sam(/usr为默认的用户主目录所在的父目录). 假 ...

  9. 用户名、密码、整数等常用的js正则表达式

    1 用户名正则 //用户名正则,4到16位(字母,数字,下划线,减号) var uPattern = /^[a-zA-Z0-9_-]{4,16}$/; //输出 true console.log(uP ...

  10. Cocoapods 版本更新与更新到指定版本

    1.本地现有的Cocoapods的版本号是1.1.0.rc.2,想升级到最新版本 1.先切换gem源 gem sources --remove https://rubygems.org/ gem so ...