Sunday, September 4, 2016

Solution to Leetcode 387. : First Unique Character in a String

Following is the link for problem statement
https://leetcode.com/problems/first-unique-character-in-a-string/

Solution:

class Solution {
public:
    int firstUniqChar(string s) {
        int valArray[26] = {0};
       
       
        for(int i=0;i<s.size();i++){
            valArray[s.at(i) - 'a'] ++;
        }
        int i=0;
        for(;i<s.size();i++){
            if (valArray[s.at(i) - 'a']  == 1){
               return i;
            }
        }
        return -1;
    }
};

Status : Accepted

Leetcode 389 Solution : Find the difference

Problem description is given in following link

https://leetcode.com/problems/find-the-difference/

Solution:

class Solution {
public:
    char findTheDifference(string s, string t) {
        int val = 0;
        for (int i=0;i<t.size();i++){
            val = val + t.at(i);
        }
       
        for (int i=0;i<s.size();i++){
            val = val - s.at(i);
        }
        return val;
    }
};

Status : Accepted

Solution Leetcode 386. Lexicographical Numbers


Following is the link to description of the problem

https://leetcode.com/problems/lexicographical-numbers/


Solution code

class Solution {
    vector<int> v;
    int limit;
private:
    void generateNos(int nos){
        if (nos > limit){
            return;
        }
       
        v.push_back(nos);
       
        for (int i=0;i<10;i++){
       
            int temp = (nos * 10) + i;
            generateNos(temp);
           
        }
        return ;
    }
public:

    vector<int> lexicalOrder(int n) {
        limit = n;
        for (int i=1;i<10;i++){
            generateNos(i);
        }
        return v;
    }
};

Time taken : 1259 msec
Status: Accepted