LintCode日記(一)——兩個字串是變位詞(C++,Python)

來源:互聯網
上載者:User

標籤:問題   python   tin   solution   通過   引入   list   ram   write   

題目描述:

寫出一個函數 anagram(s, t) 判斷兩個字串是否可以通過改變字母的順序變成一樣的字串。

解題思路:

C++:引入雜湊的思維,這道題就迎刃而解了。

C++ Code:

class Solution {
public:
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    bool anagram(string s, string t) {
        // write your code here
        int dic[58];
        for (int i = 0; i < 58; i++)
            dic[i] = 0;
        for ( int i = 0; i < s.size(); i++ )
        {
            if (s[i] == ‘ ‘)
                continue;
            int index = s[i] - ‘A‘;
            dic[index]++;
        }
        for ( int i = 0; i < t.size(); i++ )
        {
            if (t[i] == ‘ ‘)
                continue;
            int index = t[i] - ‘A‘;
            dic[index]--;
        }
        for ( int i = 0; i < 58; i++ )
        {
            if (i==57 && dic[i]==0)
                return true;
            if (dic[i] == 0)
                continue;
            else
                return false;
        }
    }
};

Python:利用Python的list()方法與sort()方法就可以成功地解決這道問題。

Python Code:

class Solution:
    """
    @param s: The first string
    @param b: The second string
    @return true or false
    """
    def anagram(self, s, t):
        # write your code here
        a = list(s)
        b = list(t)
        a.sort()
        b.sort()
        if a == b:
            return True
        else:
            return False

LintCode日記(一)——兩個字串是變位詞(C++,Python)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.