算法与数据结构之string专题

58. Length of Last Word

这是leecode的一道题,思路非常简单,刚开始一直没有想出来,睡觉前一直想终于想出来了然后第二天早上准备AC的,但是竟然效率不够,下面贴上代码

class Solution {
public:
    int lengthOfLastWord(string s) {
        int counts = 0;
        for(int i = s.length()-1;i>=0;i++)
        {
            if(s[i]!=' ')
                counts++;
            else if(counts>0)
                return counts;
        }
        return counts;
             
         
    }
};

直接Runtime Error了,可能是因为我的循环语句拖累了算法,所以,从讨论区得到了下面这个算法

class Solution {
public:
    int lengthOfLastWord(string s) {
  int len = 0, tail = s.length() - 1;
        while (tail >= 0 && s[tail] == ' ') tail--;
        while (tail >= 0 && s[tail] != ' ') {
            len++;
            tail--;
        }
        return len;   
    }
};

思路和我的算法一致但是明显能通过,说明效率高了,但是运行时间还是AC垫底的,在排行中找到了这个算法

class Solution {
public:
    int lengthOfLastWord(string s) {
        string tmp;
        stringstream ss(s);
        while (ss >> tmp) {}
        return tmp.size();
    }
};

这个代码运用了stringstream
头文件为sstream

242. Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.

初步map算法

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length()!=t.length())
            return false;
        int len = s.length();
        map<char,int>result;
        for(int i = 0;i<len;i++)
        {
            result[s[i]]++;
            result[t[i]]-- ;
        }
        for(auto res : result)
        {
            if(res.second)
                return false;
        }
        return true;
    }
};

优化算法

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length()!=t.length())
            return false;
        int len = s.length();
        int result[26] = {0};
        for(int i = 0;i<len;i++)
        {
            result[s[i]-'a']++;
            result[t[i]-'a']--;
        }
        for(int i = 0;i<26;i++)
        {
            if(result[i])
                return false;
        }
        return true;
    }
};
posted @ 2017-07-27 10:59  vhyz  阅读(146)  评论(0编辑  收藏  举报