2166. Anagrams

 

A word is called an anagram of another word if it can be obtained by rearranging its letters.

 

Input. Two words are given, each on a separate line. The words consist of lowercase Latin letters and digits. The length of each word does not exceed 100 characters.

 

Output. Print “YES” if the given words are anagrams of each other, and “NO” otherwise.

 

Sample input

Sampe output

sharm

marsh

YES

 

 

SOLUTION

sort

 

Algorithm analysis

Sort the letters in each word in lexicographical order. If the resulting sequences match, then the original words consist of the same letters and are therefore anagrams.

 

Algorithm implementation

Declare the strings s and q.

 

string s, q;

 

Read the input strings.

 

cin >> s;

cin >> q;

 

Sort the letters in each string.

 

sort(s.begin(),s.end());

sort(q.begin(),q.end());

 

Compare the resulting strings and print the answer.

 

if (s == q) puts("YES"); else puts("NO");

 

Algorithm implementation – char arrays

 

#include <cstdio>

#include <cstring>

#include <algorithm>

using namespace std;

 

char s[100], q[100];

 

int main(void)

{

  gets(s); sort(s,s+strlen(s));

  gets(q); sort(q,q+strlen(q));

  if (strcmp(s,q) == 0) puts("YES"); else puts("NO");

  return 0;

}

 

Algorithm implementation – swap sort

 

#include <stdio.h>

#include <string.h>

#define MAX 256

 

char s[MAX], q[MAX];

int slen, qlen;

 

void sort(char *m, int len)

{

  int i, j;

  char temp;

  for(i = 0; i < len; i++)

  for(j = i + 1; j < len; j++)

    if (m[i] > m[j])

    {

      temp = m[i];

      m[i] = m[j];

      m[j] = temp;

    }

}

 

int main(void)

{

  gets(s); slen = strlen(s);

  gets(q); qlen = strlen(q);

 

  sort(s,slen);

  sort(q,qlen);

 

  if (!strcmp(s,q))

    printf("YES\n");

  else

    printf("NO\n");

  return 0;

}

 

Java implementation

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    char[] s = con.nextLine().toCharArray();

    char[] q = con.nextLine().toCharArray();

 

    Arrays.sort(s);

    Arrays.sort(q);

 

    if (Arrays.equals(s, q))

      System.out.println("YES");

    else

      System.out.println("NO");

   

   con.close();   

  }

}

 

Python implementation

Read the input strings.

 

l1 = list(input())

l2 = list(input())

 

Sort the letters in each string.

 

l1.sort()

l2.sort()

 

Compare the resulting strings and print the answer.

 

if l1 == l2:

  print('YES')

else:

  print('NO')