检查字符串中给定字符出现的编号 [英] check number of a given character occurence in a String

查看:94
本文介绍了检查字符串中给定字符出现的编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个简单的类来处理字符串(可能是非常长的字符串,最多可达1mil字符)。字符串基本上由两个字符a和b组成,它们可以相互混合。如果一个相同数量的b的数量然后app会说它没关系,否则NOK。我想知道如何最有效地做到这一点。我想到使用正则表达式来分割字符串,然后计算一个和两个的出现,但也许有人知道更好的方法来做到这一点。对于正则表达式来说相对较新,所以如果有任何错误,请告诉我。这是我的早期尝试。

I want to write a simple class to process Strings (may be very long strings up to 1mil characters in it). String will basically consists of two characters "a" and "b" that may be intermingled with each other. If the number of a's equal number of b's then app will say it is OK otherwise NOK. I wonder how to do that most efficiently. I thought of using regex to split String and then count occurence of a's and b's but maybe someone knows better way to do that. Am relatively new to regex so please let me know should there be any bugs. This is my early attempt.

public class Typo { 
    public static void main(String[] args){     
        String ver = "";
        int na = 0;
        int nb = 0;
        String regex = ("\\w.+");
        Pattern p = Pattern.compile(regex);
        String text = "ababababbaba";
        if (text.length() == 0){
            ver = "OK";
        }
        else if (text.length() == 1){
            ver = "NOK";
        }
        else if ((text.length() % 2) == 1){
            ver = "NOK";
        }
        else if ((text.length() % 2) == 0){
            //check number of a and b and if it equals return OK otherwise NOK
            Matcher m1 = p.matcher("a");
            while(m1.find()){
                na = na + 1;
            }
            Matcher m2 = p.matcher("b");
            while(m2.find()){
                nb = nb + 1;
            }
            if (na == nb){
                ver = "OK";
            }
            else 
                ver = "NOK";
        }
        System.out.println(ver);
    }

}


推荐答案

为什么需要正则表达式并为此分割字符串!您可以简单地遍历字符串并计算a和bs的数量。你需要保留两个不同的计数器,一个用于a,一个用于b。使用正则表达式效率会降低。如果不至少遍历一次字符串,就无法获得结果。因此,使用一个简单的循环来计算a和b。

Why do you need regular expression and split the string for this! You can simply loop through the string and count the number of a and bs. You need to keep two different counter, one for a and one for b. Using regular expression will be less efficient. There is no way you can get the result without traversing the string at least once. So use a simple loop to count a and b.


  • 您可以在循环中进行一次优化。如果 countA - countB 的任何时间mod大于剩余字符数,则a和b永远不能相等。所以你可以打破循环。

  • You can make one optimization in the loop. If anytime mod of countA - countB is greater than the number of remaining characters then a and b can never be equal. So you can break the loop then.

如果字符串的长度为奇数,则无需计数。当元素总数为奇数时,a和b的计数永远不能相等。

If the length of the string is odd then there is no need to count. Count of a and b can never be equal when total number of elements is odd.

这篇关于检查字符串中给定字符出现的编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆