牛客網題目1:最大數

感覺做題思路還是會有一些混亂,理清思路且寫代碼要細心~
繼續多做題!!!

題目

給定一個包含大寫英文字母和數字的句子,找出這個句子所包含的最大的十六進制整數,返回這個整數的值。數據保證該整數在int表示範圍內~
https://www.nowcoder.com/questionTerminal/ac72e27f34c94856bf62b19f949b8f36

思路

  • 找到符合要求的子串,將其轉換成十六進制,更新其代表的十六進制的最大值
  • 符合要求的子串:首字母不能爲0,只能是0-9或者A-F
  • 時間複雜度O(n*2), 因爲找到子串要n的複雜度,每一個子串要轉換成十六進制是n

代碼

class Solution {
public:
    /**
     *
     * @param s string字符串
     * @return int整型
     */
    int solve(string s) {
        // write code here
        int left = 0, right = 0;
        int maxRes = INT_MIN;
        string windows;
        //cout << " init" << endl;
        while (left < s.length() && !isValidFirst(s[left])) {
            left++;
        }
        if (left == s.length())
            return 0;
        windows = s[left];
        maxRes = StringHex2int(windows);
        //cout << " find left first" << endl;
        right = left+1;
        while(right < s.length()) {
            //cout << "find right: " << right << " " << windows << endl;
            if (isValid(s[right])) {
                windows += s[right];
                if (StringHex2int(windows) > maxRes) {
                    maxRes = StringHex2int(windows);
                    //cout << windows << " "  << maxRes << endl;
                }
                // update maxRes;
            } else {
                
                left = right+1;
                while (left < s.length() && !isValidFirst(s[left])) {
                    left++;
                }
                if (left == s.length())
                    break;
                if (StringHex2int(s.substr(left, 1)) > maxRes) {
                    maxRes = StringHex2int(s.substr(left, 1));
                }
                windows=s[left];
                right = left;
            }
            right++;
        }
        return maxRes;
    }
    
    bool isValid(char c) {
        if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'))
            return true;
        return false;
    }
    
    bool isValidFirst(char c) {
        if ((c > '0' && c <= '9') || (c >= 'A' && c <= 'F'))
            return true;
        return false;
    }
    
    int StringHex2int(string s) {
        int res = 0;
        int x = 1;
        for (int i= 0; i < s.length(); i++) {
            res += Char2Hex(s[s.length()-1-i])*x;
            x*=16;
        }
        return res;
    }
    
    int Char2Hex(char c) {
        if (c >= '0' && c <= '9')
           return int(c-'0');
        else
            return int(c-'A')+10;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章