// 1221. 分割平衡字符串
// 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。
// 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
// 返回可以通过分割得到的平衡字符串的最大数量。
// 示例 1:
// 输入:s = "RLRRLLRLRL"
// 输出:4
// 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings
//考虑s也是一个平衡字符串
//这种做法不全面,但是能通过
public int balancedStringSplit(String s) {
int t = 0;
int count = 0;
char[] c = s.toCharArray();
for (char c1 : c) {
if (c1 == 'R') t++;
if (c1 == 'L') t--;
if (t == 0) count++;
}
return count;
}
//第二种做法--测试报错
public int balancedStringSplit2(String s) {
if (s.charAt(0) == 'R') return stringFind(s, "RL");
else return stringFind(s, "LR");
}
public int stringFind(String fa, String son) {
int number = 0;
int i = 0;
while (i != -1) {
int a = fa.indexOf(son);
int b = fa.indexOf(changeson(son));
if ((a != -1 && a < b) || (a != -1 && b == -1)) {
number++;
fa = fa.substring(a + 2);
}
if ((b != -1 && b < a) || (b != -1 && a == -1)) {
number++;
fa = fa.substring(b + 2);
}
if (a == -1 && b == -1) i = -1;
}
return number;
}
public String changeson(String son) {
if (son.equals("RL")) return "LR";
else return "RL";
}
leetcode-1221. 分割平衡字符串
最新推荐文章于 2024-08-22 21:49:05 发布