C++, Concise solution for (time: O(n), space: O(1))Unique Substrings in Wraparound String


  • 0
    R

    The idea is here:
    when there is a string: 'zabc', we know there are four substrings end with
    'c': 'zabc', 'abc', 'bc', 'c'
    Three substrings end with
    'b': 'zab', 'ab', 'b', and so on. Therefore, c has 4 substrings, b has 3 substrings.
    We make a table ma[26], to keep track the number of substrings end with each character.

    class Solution {
    public:
        int findSubstringInWraproundString(string p) {
            int ma[26] = {0};
            int sublen = 0;
            for(int i = 0; i < p.size(); i++){
                if(i && (p[i] - p[i-1] == 1 || p[i] - p[i-1] == -25))
                    ma[p[i] - 'a'] = max(ma[p[i]-'a'], ++sublen);
                else{
                    sublen = 1;
                    ma[p[i] - 'a'] = max(ma[p[i]-'a'], sublen);
                }
            }
            
            int res = 0;
            for(int i = 0; i<26; i++)
                res += ma[i];
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.