LeetCode 696 c# Edition(版本)

LeetCode 696      Count Binary Substrings

(本人专注于刷leetcode全部题c#语言算法,后期发视频教程)

  相信有些人看到这道题目的时候不会一下子明白。

首先解释一下题意:

    理解/核心:         1、连续的  2、数量相等

    图解:   一定要记住是连续的0和1,而不是0011 和1100 对比是一组结果。如下图:数量相等每一组结果都是偶数

LeetCode 696 c# Edition(版本)_第1张图片navy_master原创图片20180226

题目:  计数的二进制字符串的子串

Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. 

(给一个字符串S,算非空数(连续的),有0和1的数目相同的子串,和所有0的和1的在这些子串组合连续。多次出现的计数次数发生的子串。)

Substrings that occur multiple times are counted the number of times they occur.

(多次出现的计数次数发生的子串。)

Example 1:                        

Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".

Notice that some of these substrings repeat and are counted the number of times they occur.

Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

Note:

s.length will be between 1 and 50,000.s will only consist of "0" or "1" characters.

 可以把字符串s转化为0和1的堆。譬如,“11001100”转化为“2222 ”

c#版高效答案: 

 
static void Main(string[] args)
        {
            string var = "00110011";
            int num = GetNum(var);
            Console.WriteLine(num);
            Console.ReadKey();
        } 
         
        private static int GetNum(string s)
        {
            int len = s.Length;
            if (len <= 1) return 0;
            char[] sc = s.ToCharArray();
            int[] count = new int[len];
            int tmp = 0;
            for (int i = 0; i < len-1; i++)
            {
                count[tmp]++;
                if (sc[i] != sc[i + 1])
                    tmp++;
            }
            if (sc[len-1]==sc[len-2])
            
                count[tmp]++;
           
            else 
                count[tmp]++;
            int res = 0;
            for (int i = 0; i < tmp; i++)
            {
                res += Math.Min(count[i], count[i + 1]);
            }
            return res;
        }


 
  

       

   java经典答案:  http://blog.csdn.net/liuchonge/article/details/78452948

如果对答案有异议,欢迎各路大神指点,并在评论区留下c#代码,相互学习。

你可能感兴趣的:(Leetcode)