超讚字符子串


要求一個連續字串,最多隻有一個數重複出現奇數次,其他都是偶數次或者沒出現。

劍指有類似題目,通過異或=0使偶數次消去,只剩下唯一的奇數次數。但是這道題只有0-9,所以可以通過異或1<<0 (2^0)到1<<9 (2^9),得到壓縮後的status,只關注0-9是否重複出現。

(1)得到一個當前值異或後的newstatus

(2)通過依次跟1<<0到1<<9異或得到newstatus,查看之前遍歷存儲的status map裏面是否有對應的status,如果有那麼更新res,res = max(res,id-map[newstatus])

(3)如果map查不到newstatus,那麼就map[newstatus]=id 更新map (我們只需要保留該status離id最遠的那個最左端點)

class Solution {
public:
    int longestAwesome(string s) {
        if(s.length()==0){
            return 0;
        }
        unordered_map<int,int>statusid;
        int status=1<<(s[0]-'0');
        statusid[status]=0;
        statusid[0]=-1;
        int res=1;
        for(int i=1;i<s.length();i++){
            status=status^(1<<(s[i]-'0'));
            int newstatus=status;
            if(statusid.count(newstatus)){
                // cout<<i<<" "<<statusid[newstatus]<<endl;
                res=max(res,i-statusid[newstatus]);
            }
            for(int j=0;j<10;j++){
                int newstatus=status^(1<<j);
                if(statusid.count(newstatus)){
                    // cout<<i<<" "<<statusid[newstatus]<<endl;
                    res=max(res,i-statusid[newstatus]);
                }
            }
            if(statusid.count(status)){

            }else{
                statusid[status]=i;
            }
        }
        return res;        
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章