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;
}
答案 0 :(得分:0)
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.
答案 1 :(得分:0)
Complexity is O(n)
.
Don't be confused about n/2. Constant values, 1/2 in your case, should be ignored.
For example: