LeetCode(String)1221. Split a String in Balanced Strings

青旅半醒 2023-09-23 21:56 213阅读 0赞

1.问题

Balanced strings are those that have an equal quantity of ‘L’ and ‘R’ characters.

Given a balanced string s, split it into some number of substrings such that:

Each substring is balanced.
Return the maximum number of balanced strings you can obtain.
Example 1:

Input: s = “RLRRLLRLRL”
Output: 4
Explanation: s can be split into “RL”, “RRLL”, “RL”, “RL”, each substring contains same number of ‘L’ and ‘R’.

Example 2:

Input: s = “RLRRRLLRLL”
Output: 2
Explanation: s can be split into “RL”, “RRRLLRLL”, each substring contains same number of ‘L’ and ‘R’.
Note that s cannot be split into “RL”, “RR”, “RL”, “LR”, “LL”, because the 2nd and 5th substrings are not balanced.

Example 3:

Input: s = “LLLLRRRR”
Output: 1
Explanation: s can be split into “LLLLRRRR”.

Constraints:

2 <= s.length <= 1000
s[i] is either ‘L’ or ‘R’.
s is a balanced string.

2.解题思路

方法1:

解决这个问题的方法是循环遍历字符串,并在遇到时不断增加 L 和 R 的计数。
1.定义L 和 R 的计数的变量,以及返回字符串个数的变量sum
2.s转为char[] 方便遍历数组
3.如果字符等于”R“,R的计数加1,否则L的计数加1
4.R的计数=L的计数,返回字符串个数的变量sum加1
5.返回sum

方法2:

1.定义result,sum初始值为0
2.for循环遍历,如果s的元素为L,sum为1;如果为R,为-1
3.sum中R和L的个数和为0,result加一
4.返回值result

3.代码

代码1:

  1. class Solution {
  2. public int balancedStringSplit(String s) {
  3. int countR = 0;//1.定义L 和 R 的计数的变量,以及返回字符串个数的变量sum
  4. int countL =0;
  5. int sum=0;
  6. char[] d = s.toCharArray();//2.s转为char[] 方便遍历数组
  7. for(int i =0;i<d.length;i++){
  8. if(d[i]=='R'){
  9. //3.如果字符等于”R“,R的计数加1,否则L的计数加1
  10. countR++;
  11. }else{
  12. countL++;
  13. }
  14. if(countR == countL){
  15. //4.R的计数=L的计数,返回字符串个数的变量sum加1,
  16. sum++;
  17. }
  18. }
  19. return sum;//5.返回sum
  20. }
  21. }

代码2:

  1. class Solution {
  2. public int balancedStringSplit(String s) {
  3. int result = 0, sum = 0;//1.定义result,sum初始值为0
  4. for (int i = 0; i < s.length(); i++) {
  5. //2.for循环遍历,如果s的元素为L,sum为1;如果为R,为-1
  6. sum += s.charAt(i) == 'L' ? 1 : -1;
  7. if (sum == 0) result++;//3.sum中R和L的个数和为0,result加一
  8. }
  9. return result;//4.返回值result
  10. }
  11. }

以下代码和代码2的解题思路相同

  1. class Solution {
  2. public int balancedStringSplit(String s) {
  3. int result = 0;
  4. int sum = 0;
  5. for (char letter : s.toCharArray()) {
  6. sum += (letter == 'R' ? 1 : -1);
  7. if (sum == 0) {
  8. result++;
  9. }
  10. }
  11. return result;
  12. }
  13. }

发表评论

表情:
评论列表 (有 0 条评论,213人围观)

还没有评论,来说两句吧...

相关阅读

    相关 String split方法

    split 分割 把一个字符串按照规则进行分割开 文档中有两种格式,返回类型是String\[\],用了存储分割后的字符串 1  `split(String regex)

    相关 Stringsplit方法

    split方法是一个最常用的拆分字符串的方法。如果没有深入了解的话,就会采坑。 笔者前几天在项目中就遇到了这个坑,一直以为带一个分隔符的字符串,无论左右两侧是否有字符