字符串中第二大的数字【LC1796】
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
快快学完今天的,然后去做菜
- 思路:遍历字符串,使用变量记录字符串中第一大firstH和第二大的整数值secondH,当遇到一个整数num时进行判断
。当num>firstH时,num即为当前数组第一大,firstH为第二大
。当num<firstH并且num>secondH时,num即为当前数组第二大
。注意:当num==firstH时,不做任何处理
- 实现
class Solution { public int secondHighest(String s) { int firstH = -1; int secondH = -1; for (char c : s.toCharArray()){ if (c >= '0' && c <= '9'){ int num = c -'0'; if (num > firstH) { secondH = firstH; firstH = num; }else if (num < firstH && num > secondH) { secondH = num; } } } return secondH; } }
。复杂度
- 时间复杂度:O ( n )
- 空间复杂度:O ( 1 )