Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, December 4, 2017

Count substring start and end with 1


Problem:
“00100101”, then there are three substrings “1001”, “100101” and “101”

Idea : count no. of 1 
answer is n*(n-1)/2


Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
 {
     public static int subStr(String str)
     {
         int c=0;
         for(int i=0;i<str.length();++i)
         {
             if(str.charAt(i)=='1')
             ++c;
         }
         return (c*(c-1))/2;
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
    System.out.println(subStr(ab.next()));
}
}
}

0 Comments:

Post a Comment

Stats