1374. 生成每种字符都是奇数个的字符串 给你一个整数 n,请你返回一个含 n 个字符的字符串,其中每种字符在该字符串中都恰好出现 奇数次 。 返回的字符串必须只含小写英文字母。如果存在多个满足题目要求的字符串,则返回其中任意一个即可。 示例 1: 输入:n = 4 输出:"pppz" 解释:"pppz" 是一个满足题目要求的字符串,因为 'p' 出现 3 次,且 'z' 出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ohhh" 和 "love"。 示例 2: 输入:n = 2 输出:"xy" 解释:"xy" 是一个满足题目要求的字符串,因为 'x' 和 'y' 各出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ag" 和 "ur"。 示例 3: 输入:n = 7 输出:"holasss" https://leetcode.cn/problems/generate-a-string-with-characters-that-have-odd-counts/
题解:
public String generateTheString(int n) {
StringBuilder sb = new StringBuilder();
if (n % 2 == 1){
return sb.append("a".repeat(n)).toString();
}
return sb.append("a".repeat(n-1)).append("b").toString();
}
1528. 重新排列字符串 给你一个字符串 s 和一个 长度相同 的整数数组 indices 。 请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。 返回重新排列后的字符串。 示例 1: 输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3] 输出:"leetcode" 解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。 示例 2: 输入:s = "abc", indices = [0,1,2] 输出:"abc" 解释:重新排列后,每个字符都还留在原来的位置上。 https://leetcode.cn/problems/shuffle-string/
题解:
public String restoreString(String s, int[] indices) {
char res [] = new char[s.length()];
for (int i=0;i<indices.length;i++){
res[indices[i]] = s.charAt(i);
}
return new String(res);
}
1221. 分割平衡字符串 在一个 平衡字符串 中,'L' 和 'R' 字符的数量是相同的。 给你一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。 注意:分割得到的每个字符串都必须是平衡字符串,且分割得到的平衡字符串是原平衡字符串的连续子串。 返回可以通过分割得到的平衡字符串的 最大数量 。 示例 1: 输入:s = "RLRRLLRLRL" 输出:4 解释:s 可以分割为 "RL"、"RRLL"、"RL"、"RL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 示例 2: 输入:s = "RLLLLRRRLR" 输出:3 解释:s 可以分割为 "RL"、"LLLRRR"、"LR" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 示例 3: 输入:s = "LLLLRRRR" 输出:1 解释:s 只能保持原样 "LLLLRRRR". 示例 4: 输入:s = "RLRRRLLRLL" 输出:2 解释:s 可以分割为 "RL"、"RRRLLRLL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 https://leetcode.cn/problems/split-a-string-in-balanced-strings
题解:
public int balancedStringSplit(String s) {
int num = 0, n = 0;
for (int i=0;i<s.length();i++){
if (s.charAt(i)=='R') n++;
if (s.charAt(i)=='L') n--;
if (n == 0) num++;
}
return num;
}