Open Zheaoli opened 2 years ago
class Solution {
public String reformat(String s) {
char[] chs = s.toCharArray();
int n = chs.length, cnt = 0;
for (char ch : chs) {
if (ch >= 'a' && ch <= 'z') {
cnt++;
}
}
if (cnt != n >> 1 && cnt != (n + 1) >> 1) {
return "";
}
int i = 0, j = 0;
char[] letters = new char[cnt], nums = new char[n - cnt];
for (char ch : chs) {
if (ch >= 'a' && ch <= 'z') {
letters[i++] = ch;
} else {
nums[j++] = ch;
}
}
if ((n & 1) == 1 && cnt > n - cnt) {
i = 0;
j = 1;
} else {
j = 0;
i = 1;
}
for (int idx = 0; idx < letters.length; idx++, i += 2) {
chs[i] = letters[idx];
}
for (int idx = 0; idx < nums.length; idx++, j += 2) {
chs[j] = nums[idx];
}
return new String(chs);
}
}
WeChat:Saraad
/*
* @lc app=leetcode id=169 lang=typescript
*
* [169] Majority Element
*/
// @lc code=start
function majorityElement(nums: number[]): number {
// const numCounter = {};
// for (let i = 0; i < nums.length; i++) {
// const n = nums[i];
// if (!numCounter[n]) {
// numCounter[n] = 1;
// }
// if (numCounter[n] > nums.length / 2) {
// return n;
// }
// numCounter[n]++;
// }
let counter = 0;
let target = 0;
// if the size of the target number greater than n / 2
// then it will last till then end
for (let i = 0; i < nums.length; i++) {
const n = nums[i];
if (counter === 0) {
target = n;
}
if (n === target) {
counter++;
} else {
counter--;
}
}
return target;
};
// @lc code=end
微信id: 弘树 来自 vscode 插件
#
# @lc app=leetcode.cn id=1417 lang=python3
#
# [1417] 重新格式化字符串
#
# @lc code=start
from string import digits
class Solution:
def reformat(self, s: str) -> str:
n = len(s)
cache_letters = []
cache_nums = []
for c in s:
if c in digits:
cache_nums.append(c)
else:
cache_letters.append(c)
if len(cache_letters) in (len(cache_nums), len(cache_nums) - 1):
return "".join(
cache_letters.pop()
if i % 2 else
cache_nums.pop()
for i in range(n)
)
if len(cache_letters) - 1 == len(cache_nums):
return "".join(
cache_nums.pop()
if i % 2 else
cache_letters.pop()
for i in range(n)
)
return ""
# @lc code=end
微信id: 而我撑伞 来自 vscode 插件
class Solution {
public String reformat(String s) {
int n = s.length();
char[] chars = s.toCharArray();
int digitNum = 0;
for (int i = 0; i < n; i++) {
if (Character.isDigit(chars[i])) {
digitNum++;
}
}
int charNum = n - digitNum;
if (Math.abs(digitNum - charNum) > 1) {
return "";
}
boolean flag = digitNum > charNum;
int i = flag ? 0 : 1; // 数字下标
int j = 1 - i; // 字母下标
while (i < n && j < n) {
while (i < n && Character.isDigit(chars[i])) {
i += 2;
}
while (j < n && !Character.isDigit(chars[j])) {
j += 2;
}
if (i < n && j < n) {
swap(chars, i, j);
}
}
return String.valueOf(chars);
}
private void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
2022-08-11