每日一题 分割平衡字符串String.charAt()影响时间

    //为何第二次和第三次消耗时间还是有差距呢因为每次调用charAt时候都会将String转换为char[]数组所以直接一次转换完成后再去通过index取值就可以了

提交时间

提交结果

执行用时

内存消耗

语言

几秒前通过1 ms36.8 MBJava

6 分钟前编译出错N/AN/AJava

7 分钟前通过0 ms37.8 MBJava

9 分钟前通过1 ms37.8 MB

Java9 分钟前编译出错N/AN/AJava

String.charAt源码

    /** The value is used for character storage. 
    private final char value[];
         if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
        */

 

在一个「平衡字符串」中,'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".
 

提示:

1 <= s.length <= 1000
s[i] = 'L' 或 'R'
分割得到的每个字符串都必须是平衡字符串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings

class Solution {
    public int balancedStringSplit(String s) {
    //     int l  = 0;
	// int r = 0;
	// 	int count = 0;

	// 	for(int i = 0;i<s.length();i++){
	// 		if(s.charAt(i)=='L'){
	// 			l++;
	// 		}
	// 		if(s.charAt(i)=='R'){
	// 			r++;
	// 		}
	// 		if(l==r){
	// 			l=0;
	// 			r=0;
	// 			count++;
	// 		}

	// 	}

	// 	return count;
     // 「平衡字符串」中,'L' 和 'R' 字符的数量是相同的
        // char[] chars = s.toCharArray();
        // int cnt = 0;
        // int balance = 0;
        // for(int i = 0; i < chars.length; i++){
        //     if(chars[i] == 'L') {
        //         balance--;
        //     }
        //     if(chars[i] == 'R') {
        //         balance++;
        //     }
        //     if(balance == 0) {
        //         cnt++;
        //     }
        // }
        // return cnt;

        //为何第二次个这次还是有差距呢因为每次调用charAt时候都会将String转换为char[]数组所以直接一次转换完成后再去通过index取值就可以了
        int cnt = 0;
        int balance = 0;
        for(int i = 0; i < s.length(); i++){
          if(s.charAt(i)=='L'){
	 			balance++;
			}
		if(s.charAt(i)=='R'){
	 			balance--;
			}
            if(balance == 0) {
                cnt++;
            }
        }
        return cnt;


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值