简体   繁体   中英

What will be the time complexity of this function?

This is the function to check the string of pattern a^nb^n.

Input : str = "aabb" Output : Yes

Input : str = "abab" Output : No

Input : str = "aabbb" Output : No

Can someone please help determine the time complexity? As the loop will run n/2 times , is it still linear ?

 public static boolean isAnBn(String s)
    {
        int l = s.length();

        // Only even length strings will have same number of a's and b's
        if (l%2 == 1)
        {
            return false;
        }
        // Set two pointers, one from the left and another from right
        int i = 0;
        int j = l-1;

        // Compare the characters till the center
        while (i<j)
        {
            if(s.charAt(i) != 'a' || s.charAt(j) != 'b')
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

Yes, it will still be linear time. In the worse case, you'll have to go through each character if i is never equal to 'a' or j is never 'b' . When it comes to big O think about the worse case. I hope that helps.

Complexity is O(n) .

Don't be confused about n/2. Constant values, 1/2 in your case, should be ignored.

For example:

  • n/2 = O(n)
  • 3n = O(n)
  • 10000000n = O(n)
  • etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM