LeetCode(String)2315. Count Asterisks
1.问题
You are given a string s, where every two consecutive vertical bars ‘|’ are grouped into a pair. In other words, the 1st and 2nd ‘|’ make a pair, the 3rd and 4th ‘|’ make a pair, and so forth.
Return the number of ‘’ in s, excluding the ’ between each pair of ‘|’.
Note that each ‘|’ will belong to exactly one pair.
Example 1:
Input: s = “l|eet|co|*de|" Output: 2 Explanation: The considered characters are underlined: "l|eet|co|*de|”. The characters between the first and second ‘|’ are excluded from the answer. Also, the characters between the third and fourth ‘|’ are excluded from the answer. There are 2 asterisks considered. Therefore, we return 2.
Example 2:
Input: s = “iamprogrammer” Output: 0 Explanation: In this example, there are no asterisks in s. Therefore, we return 0.
Example 3:
Input: s = “yo|uar|e**|b|eau|tifu|l" Output: 5 Explanation: The considered characters are underlined: "yo|uar|e|b|e**au|tifu|l”. There are 5 asterisks considered. Therefore, we return 5.
Constraints:
1 <= s.length <= 1000 s consists of lowercase English letters, vertical bars ‘|’, and asterisks ‘*’. s contains an even number of vertical bars ‘|’.
2. 解题思路
方法1:
1.定义"|" 和""的计数器 2.将字符串转换为字符数组 3.如果当前字符是 “|”,将 “|” 的计数器加1 4.如果 “|” 的数量是偶数,统计 "" 的数量并且当前字符是 “",将 "” 的计数器加1 5.返回 “*” 的计数器
方法2:
1.标记当前字符是否在 “|” 内部 2.统计在偶数个 “|” 之间的 “" 的数量 3.如果当前字符是 “|”,则切换 “insidePipe” 的状态 4.如果当前字符不在 “|” 内部,并且是 "”,则将 “" 的计数器加1 5.返回 "” 的计数器
3. 代码
代码1:
class Solution { public int countAsterisks(String s) { int bar_count = 0; // "|" 的计数器 int asterisk_count = 0; // "*" 的计数器 char[] char_arr = s.toCharArray(); // 将字符串转换为字符数组 // 遍历字符串 for (int i = 0; i < s.length(); i++) { if(char_arr[i] == |){ bar_count++; // 如果当前字符是 "|",将 "|" 的计数器加1 } // 如果 "|" 的数量是偶数,统计 "*" 的数量 if(bar_count % 2 ==0&&char_arr[i] == *){ asterisk_count++; // 如果当前字符是 "*",将 "*" 的计数器加1 } } return asterisk_count; // 返回 "*" 的计数器 } }
代码2:
class Solution { public int countAsterisks(String s) { boolean insidePipe = false; // 1.标记当前字符是否在 "|" 内部 int count = 0; // 2.统计在偶数个 "|" 之间的 "*" 的数量 for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == |){ insidePipe = !insidePipe; // 3.如果当前字符是 "|",则切换 "insidePipe" 的状态 } if(!insidePipe && s.charAt(i) == *){ count++; // 4.如果当前字符不在 "|" 内部,并且是 "*",则将 "*" 的计数器加1 } } return count; // 5.返回 "*" 的计数器 } }
上一篇:
92天倒计时,蓝桥杯省赛备赛攻略来啦~
下一篇:
Java程序员的就业方向