码迷,mamicode.com
首页 > 其他好文 > 详细

字符串中第二大的数

时间:2021-04-14 12:31:36      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:problems   target   color   solution   git   tco   组成   nbsp   for   

此博客链接:

字符串中第二大的数

题目链接:https://leetcode-cn.com/problems/second-largest-digit-in-a-string/

题目

给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

混合字符串 由小写英文字母和数字组成。

 

示例 1:

输入:s = "dfa12321afd"
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
示例 2:

输入:s = "abc1111"
输出:-1
解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
 

题解

使用两个指针,第一个指针,指向最大值,第二个指针指向次大值。这里最难的部分是如果处理第二小的数,这里采用先把第一个数赋值,,然后每次判断数字是否大于第一个数,如果是,则更新最大值,并把第一个数的值赋值给第二个数,如果当前的数小于第一个数并且大于第二个数,则把这个数赋值给第二个数。

注意:我是采用的数字的ASSII码,最后先判断第二个数的值是否为-1,如果为-1表明没有第二大的数,返回-1,如果不为-1,则返回第二个数的数值(即数字的ASII码减去48)

代码

class Solution {
    public int secondHighest(String s) {
        int max=-1;
        int maxtwo=-1;
        char ch[]=new char[s.length()];
        for(int i=0;i<s.length();i++)
        { 
               ch[i]=s.charAt(i);
            
         
            if(ch[i]<a)
            {
                if(max==-1)
                {
                    max=ch[i];
                }
                // System.out.println(ch[i]);
                 if(ch[i]>max)
                {
                    maxtwo=max;
                    max=ch[i];

                    //  System.out.println(max);
                }
              else if (ch[i]>maxtwo&&ch[i]<max){
                    
                    maxtwo=ch[i];
                    //  System.out.println(maxtwo);
                }
            }
        }
        if(maxtwo==-1)
        return -1;
        int res=maxtwo-48;
        // if(res!=-1)
             return res;
        // return -1;
        

    }
}

 

结果

技术图片

 

字符串中第二大的数

标签:problems   target   color   solution   git   tco   组成   nbsp   for   

原文地址:https://www.cnblogs.com/ping2yingshi/p/14656032.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!