Skip to content

Commit aa91ff3

Browse files
committed
#2124: Check if All A's Appears Before All B's; solution & tests.
1 parent 6cb7828 commit aa91ff3

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* 2124
3+
* Check if All A's Appears Before All B's
4+
**
5+
* Given a string s consisting of only the characters 'a' and 'b',
6+
* return true if every 'a' appears before every 'b' in the string.
7+
* Otherwise, return false.
8+
*
9+
* Example 1:
10+
* Input: s = "aaabbb"
11+
* Output: true
12+
* Explanation:
13+
* The 'a's are at indices 0, 1, and 2,
14+
* while the 'b's are at indices 3, 4, and 5.
15+
* Hence, every 'a' appears before every 'b' and
16+
* we return true.
17+
*
18+
* Example 2:
19+
* Input: s = "abab"
20+
* Output: false
21+
* Explanation:
22+
* There is an 'a' at index 2 and a 'b' at index 1.
23+
* Hence, not every 'a' appears before every 'b' and
24+
* we return false.
25+
*
26+
* Example 3:
27+
* Input: s = "bbb"
28+
* Output: true
29+
* Explanation:
30+
* There are no 'a's, hence, every 'a' appears before every 'b' and
31+
* we return true.
32+
*
33+
* Constraints:
34+
* • 1 <= s.length <= 100
35+
* • s[i] is either 'a' or 'b'.
36+
*
37+
* Hint 1:
38+
* You can check the opposite:
39+
* check if there is a ‘b’ before an ‘a’.
40+
* Then, negate and return that answer.
41+
*
42+
* Hint 2:
43+
* s should not have any occurrences of “ba” as a substring.
44+
**
45+
* https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/
46+
***/
47+
48+
namespace Problems;
49+
50+
public class CheckIfAllAAppearsBeforeAllB
51+
{
52+
public bool CheckString( string s )
53+
{
54+
for ( int i = 1; i < s.Length; i++ )
55+
{
56+
if ( s[i - 1] == 'b' && s[i] == 'a' )
57+
{
58+
return false;
59+
}
60+
}
61+
62+
return true;
63+
}
64+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class CheckIfAllAAppearsBeforeAllBTests
6+
{
7+
[TestCase( "aaabbb", ExpectedResult = true )]
8+
[TestCase( "abab", ExpectedResult = false )]
9+
[TestCase( "bbb", ExpectedResult = true )]
10+
[TestCase( "aaa", ExpectedResult = true )]
11+
public bool CheckStringTest( string s ) =>
12+
new CheckIfAllAAppearsBeforeAllB().CheckString( s );
13+
}

0 commit comments

Comments
 (0)