for Robot Artificial Inteligence

16. Valid Palindrome Solution

|

class Solution {
public:
    bool isPalindrome(string s) {
        for(int i=0, j=s.size() -1 ; i<j; i++, j--)
        {
            while(isalnum(s[i])==false && i<j) i++;
            while(isalnum(s[j])==false && i<j) j--;
            if(toupper(s[i])!=toupper(s[j])) return false;
        }
        return true;
    }
};
  • Move 2 pointers from each end until they collide
  • Increment left pointer if not alphanumeric(숫자나 글자가 아닐경우)
  • decrement right pointer if not alphanumeric(숫자나 글자가 아닐경우)
  • Exit and return error if not match

Comment  Read more

15. Valid Anagram

|

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size())
        {
            return false;
        }
        unordered_map<char, int> mp;
        int check=0;
        for(auto& c : s)
        {
            mp[c]++;
        }
        for(auto& c : t)
        {
            if(mp[c]>=1)
            {
                mp[c]--;
                check++;
            }

        }
        cout<<check<<", "<< s.size();
        if(check==s.size())
        {
            return true;
        }
        else
        {
            return false;
        }

    }
};
  • store counts of every character into the hash table, second time, find the first character that appears

Comment  Read more

14. First Unique Character in a String

|

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, int> mp;
        for(auto& c : s)
        {
            mp[c]++;
        }
        for(int i =0; i<s.size(); i++)
        {
            if(mp[s[i]]==1)
                return i;
        }
        return -1;

    }
};
  • Brute force solution, traverse string s 2 times. First time, store counts of every character into the hash table, second time, find the first character that appears only once.

Comment  Read more

13. Reverse Integer

|

class Solution {
public:
    int reverse(int x) {
        long int result = 0;
        while(x)
        {
            result = result*10 + x%10;
            x/=10;
        }
        if(result>INT_MAX || result<INT_MIN)
        {
            return 0;
        }
        return result;

    }
};

Comment  Read more

12. Reverse String

|

class Solution {
public:
    void reverseString(vector<char>& s) {
        vector<char> copy;
        for(char i : s)
        {
            copy.insert(copy.begin(), i);
        }
        s = copy;

    }
};

Comment  Read more