767. 重构字符串
前言题目源码
前言
今天的题目说是排序也对,主要还是要对字符进行一个间隔处理。
题目
官方题目
源码
class Solution {
public String
reorganizeString(String S
) {
int len
=S
.length();
int []count
=new int[26];
for (char c
:S
.toCharArray()) count
[c
-'a']+=100;
for(int i
=0;i
<26;++i
) count
[i
]+=i
;
Arrays
.sort(count
);
char []ans
=new char[len
];
int t
=1;
for(int cur
:count
){
int ct
= cur
/100;
char c
=(char)((cur
%100)+'a');
if (ct
>(len
+1)/2){
return "";
}
for(int i
=0;i
<ct
;++i
){
if(t
>=len
) t
=0;
ans
[t
]=c
;
t
+=2;
}
}
return String
.valueOf(ans
);
}
}
class Solution:
def reorganizeString(self
, S
: str) -> str:
N
= len(S
)
A
= []
for c
, x
in sorted((S
.count
(x
), x
) for x
in set(S
)):
if c
> (N
+1)/2: return ""
A
.extend
(c
* x
)
ans
= [None] * N
ans
[::2], ans
[1::2] = A
[int(N
/2):], A
[:int(N
/2)]
return "".join
(ans
)
转载请注明原文地址: https://lol.8miu.com/read-21782.html