TDD LeetCode:771. Jewels and Stones
RojerChen.2018.09.12
You're given strings
You're given strings
J
representing the types of stones that are jewels, and S
representing the stones you have. Each character in S
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in
J
are guaranteed distinct, and all characters in J
and S
are letters. Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
Example 1:
Input: J = "aA", S = "aAAbbbb" Output: 3
Example 2:
Input: J = "z", S = "ZZ" Output: 0
Note:
S
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
Step1 新增一個類別庫
public class Algorithm
{
public int numJewelsInStones(string J, string S)
{
return 3;
}
}
Step2 新增測試案例
依據題目給的測試條件,測試案例如下[TestMethod]
public void TestMethod1()
{
Algorithm alg = new Algorithm();
string firstParam = "aA";
string secondParam = "aAAbbbb";
int expected = 3;
int actual = alg.numJewelsInStones(firstParam, secondParam);
Assert.AreEqual(expected, actual);
}
執行測試,測試通過Step3 再新增一個測試案例
依據題目,第二個測試案例如下[TestMethod]
public void TestMethod2()
{
Algorithm alg = new Algorithm();
string firstParam = "z";
string secondParam = "ZZ";
int expected = 0;
int actual = alg.numJewelsInStones(firstParam, secondParam);
Assert.AreEqual(expected, actual);
}
想當然這次測試不通過了,所以回頭開始調整原本的程式Step4 調整程式邏輯
調整程式碼邏輯public int numJewelsInStones(string J, string S)
{
int counter = 0;
for (int i = 0; i < J.Length; i++)
{
for (int j=0;j<S.Length;j++)
{
if (J.Substring(i, 1) == S.Substring(j, 1))
{
counter += 1;
}
}
}
return counter;
}
測試通過。
0 意見:
張貼留言