[程式語言] C++

[演算法]

Algorithm A.

兩字串若是由相同的字元之間以不同順序組成,則必符合兩個條件:

  1. 字元數目相等。
  2. 字元轉成小寫後以其代表的整數值加總後的和,兩字串必相等。

符合以上二條件即表示二字串互為Anagrams.

Algorithm B.

另一比較傳統的方式則是把兩字串各重新排列字母,由大到小或由小到大皆可,只要排列之後兩字串結果相同,則互為Anagrams.

[程式架構]

  1. Main() function: 程式入口,要求輸入兩字串然後印出兩字串是否為Anagrams.
  2. bool isAnagram( s1, s2) function :

    Step 1. 判斷兩字串是否字元數相等,若不相等則 return false,相等則繼續下一步。.

    Step 2. 判斷兩字串的整數值是否相等,若相等則 return true,不相等則return false.

  1. int countString( str) function: 傳入一個字串,然後計算該字串所有字元整數值的總和並回傳給caller .

[程式碼] isAnagrams.cpp

My Git Hub https://github.com/jackterrylau/SchoolCode/blob/master/CPP/IsAnagrams.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "stdafx.h"     // Visual Studio as IDE.
#include <iostream>
#include <string>
using namespace std;

int countString(const string& original)
{
     int count=0;
     for (int i = 0; i < original.length(); i++)
     {
         count += int(tolower(original[i])); // 把所有大寫字母轉小寫再加總.
     }

     return count;
}

bool isAnagram(const string& s1, const string& s2)
{
     string sorts;
     if (s1.length() == s2.length())
     {
         if (countString(s1) == countString(s2)) return true;
     }

     return false;
}

int main()
{
     string s1, s2;
     cout << "Enter a string s1: ";
     cin >> s1;
     cout << "Enter a string s2: ";
     cin >> s2;

     if (isAnagram(s1, s2)) cout << s1 << " and " << s2 << " are anagrams." << endl;
     else cout << s1 << " and " << s2 << " are not anagrams." << endl;

     system("pause");
     return 0;
}

 

 

arrow
arrow

    jackterrylau 發表在 痞客邦 留言(0) 人氣()