Two words equals one word

1880. Check if Word Equals Summation of Two Words

中文文档

Description

The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).

The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.

  • For example, if s = "acb", we concatenate each letter’s letter value, resulting in "021". After converting it, we get 21.

You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.

Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.

Example 1:

Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.

Example 2:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation: 
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.

Example 3:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
Output: true
Explanation: 
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aaaa" -> "0000" -> 0.
We return true because 0 + 0 == 0.

Constraints:

  • 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
  • firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.

Solutions

Python3

class Solution:
    def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
        def f(s):
            res = 0
            for c in s:
                res = res * 10 + (ord(c) - ord('a'))
            return res

        return f(firstWord) + f(secondWord) == f(targetWord)

Java

class Solution {
    public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
        return f(firstWord) + f(secondWord) == f(targetWord);
    }

    private int f(String s) {
        int res = 0;
        for (char c : s.toCharArray()) {
            res = res * 10 + (c - 'a');
        }
        return res;
    }
}

C++

class Solution {
public:
    bool isSumEqual(string firstWord, string secondWord, string targetWord) {
        return f(firstWord) + f(secondWord) == f(targetWord);
    }

    int f(string s) {
        int res = 0;
        for (char c : s) res = res * 10 + (c - 'a');
        return res;
    }
};

Go

func isSumEqual(firstWord string, secondWord string, targetWord string) bool {
	f := func(s string) int {
		res := 0
		for _, c := range s {
			res = res*10 + int(c-'a')
		}
		return res
	}
	return f(firstWord)+f(secondWord) == f(targetWord)
}

JavaScript

/**
 * @param {string} firstWord
 * @param {string} secondWord
 * @param {string} targetWord
 * @return {boolean}
 */
var isSumEqual = function (firstWord, secondWord, targetWord) {
    function f(s) {
        let res = 0;
        for (let c of s) {
            res = res * 10 + (c.charCodeAt() - 'a'.charCodeAt());
        }
        return res;
    }
    return f(firstWord) + f(secondWord) == f(targetWord);
};

TypeScript

function isSumEqual(
    firstWord: string,
    secondWord: string,
    targetWord: string,
): boolean {
    const calc = (s: string) => {
        let res = 0;
        for (const c of s) {
            res = res * 10 + c.charCodeAt(0) - 'a'.charCodeAt(0);
        }
        return res;
    };
    return calc(firstWord) + calc(secondWord) === calc(targetWord);
}

Rust

impl Solution {
    fn calc(s: &String) -> i32 {
        let mut res = 0;
        for c in s.as_bytes() {
            res = res * 10 + (c - b'a') as i32;
        }
        res
    }

    pub fn is_sum_equal(first_word: String, second_word: String, target_word: String) -> bool {
        Self::calc(&first_word) + Self::calc(&second_word) == Self::calc(&target_word)
    }
}

C

int calc(char *s) {
    int res = 0;
    for (int i = 0; s[i]; i++) {
        res = res * 10 + s[i] - 'a';
    }
    return res;
}

bool isSumEqual(char *firstWord, char *secondWord, char *targetWord) {
    return calc(firstWord) + calc(secondWord) == calc(targetWord);
}

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given three strings A, B, and C of size L, M, and N respectively and consisting of only lower case English alphabets less than ‘K’. The task is to check if the sum of strings A and B is equal to the string C after decoding the strings into integers by mapping alphabets with their index value in the list of alphabets and concatenating them.

    Examples:

    Input: A = “acb”, B = “cba”, C = “cdb”
    Output: Yes
    Explanation:

    1. The string A, modifies to integer 021 after replacing the characters ‘a’, ‘b’ and ‘c’ with their index values in the list of alphabets i.e 0, 1 and 2.
    2. The string B, modifies to integer 210 after replacing the characters ‘a’, ‘b’ and ‘c’ with their index values in the list of alphabets i.e 0, 1 and 2.
    3. The string C, modifies to integer 231 after replacing the characters ‘b’, ‘c’ and ‘d’ with their index values in the list of alphabets i.e 1, 2 and 3.

    The sum of strings A and B i.e (21+210 = 231) is equal to 231, which is the value of string C. Therefore, print “Yes”.

    Input: A = “aaa”, B = “bcb”, C = “bca”
    Output: No

    Approach: The problem can be solved using a similar approach used in finding the sum of two large numbers represented as strings. Follow the steps below to solve the problem:

    • Reverse the strings A, B, and C.
    • Initialize two variables, say curr and rem as 0 to store the value at ith position and the remainder of the sum of the strings A and B.
    • Iterate over the range [0, max(L, max(M, N))] using the variable i and performing the following steps:
      • Store the sum of characters at the ith index of the strings A and B in the variable curr.
      • Update curr as curr = curr+rem and then update rem as rem = curr/10.
      • Now check if i is less than N and curr%10 is not equal to the C[i]-‘a’ i.e value at the ith character of the string C, then print “No” and return.
    • Finally, after completing the above steps, if rem is greater than 0 then print “No“. Otherwise, print “Yes“.

    Below is the implementation of the above approach:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    string isSumEqual(string A, string B, string C)

    {

        int L = A.length();

        int M = B.length();

        int N = A.length();

        reverse(A.begin(), A.end());

        reverse(B.begin(), B.end());

        reverse(C.begin(), C.end());

        int rem = 0;

        for (int i = 0; i < max(L, max(M, N)); i++) {

            int curr = rem;

            if (i < L)

                curr += A[i] - 'a';

            if (i < M)

                curr += B[i] - 'a';

            rem = curr / 10;

            curr %= 10;

            if (i < N && curr != C[i] - 'a') {

                return "No";

            }

        }

        if (rem)

            return "No";

        else

            return "Yes";

    }

    int main()

    {

        string A = "acb", B = "cba", C = "cdb";

        cout << isSumEqual(A, B, C);

        return 0;

    }

    Java

    import java.util.*;

    class GFG{

    static String isSumEqual(String A, String B, String C)

    {

        int L = A.length();

        int M = B.length();

        int N = A.length();

        A = reverse(A);

        B = reverse(B);

        C = reverse(C);

        int rem = 0;

        for (int i = 0; i < Math.max(L, Math.max(M, N)); i++) {

            int curr = rem;

            if (i < L)

                curr += A.charAt(i) - 'a';

            if (i < M)

                curr += B.charAt(i) - 'a';

            rem = curr / 10;

            curr %= 10;

            if (i < N && curr != C.charAt(i) - 'a') {

                return "No";

            }

        }

        if (rem>0)

            return "No";

        else

            return "Yes";

    }

    static String reverse(String input) {

        char[] a = input.toCharArray();

        int l, r = a.length - 1;

        for (l = 0; l < r; l++, r--) {

            char temp = a[l];

            a[l] = a[r];

            a[r] = temp;

        }

        return String.valueOf(a);

    }

    public static void main(String[] args)

    {

        String A = "acb", B = "cba", C = "cdb";

        System.out.print(isSumEqual(A, B, C));

    }

    }

    Python3

    def isSumEqual(A, B, C):

        L = len(A)

        M = len(B)

        N = len(A)

        A = A[::-1]

        B = B[::-1]

        C = C[::-1]

        rem = 0

        for i in range(max(L, max(M, N))):

            curr = rem

            if (i < L):

                curr += ord(A[i]) - ord('a')

            if (i < M):

                curr += ord(B[i]) - ord('a')

            rem = curr // 10

            curr %= 10

            if (i < N and curr != ord(C[i]) - ord('a')):

                return "No"

        if (rem):

            return "No"

        else:

            return "Yes"

    if __name__ == '__main__':

        A = "acb"

        B = "cba"

        C = "cdb"

        print (isSumEqual(A, B, C))

    C#

    using System;

    public class GFG{

    static String isSumEqual(String A, String B, String C)

    {

        int L = A.Length;

        int M = B.Length;

        int N = A.Length;

        A = reverse(A);

        B = reverse(B);

        C = reverse(C);

        int rem = 0;

        for (int i = 0; i < Math.Max(L, Math.Max(M, N)); i++) {

            int curr = rem;

            if (i < L)

                curr += A[i] - 'a';

            if (i < M)

                curr += B[i] - 'a';

            rem = curr / 10;

            curr %= 10;

            if (i < N && curr != C[i] - 'a') {

                return "No";

            }

        }

        if (rem>0)

            return "No";

        else

            return "Yes";

    }

    static String reverse(String input) {

        char[] a = input.ToCharArray();

        int l, r = a.Length - 1;

        for (l = 0; l < r; l++, r--) {

            char temp = a[l];

            a[l] = a[r];

            a[r] = temp;

        }

        return String.Join("",a);

    }

    public static void Main(String[] args)

    {

        String A = "acb", B = "cba", C = "cdb";

        Console.Write(isSumEqual(A, B, C));

    }

    }

    Javascript

    <script>

    function isSumEqual(A, B, C) {

        let L = A.length;

        let M = B.length;

        let N = A.length;

        A.split("").reverse().join("");

        B.split("").reverse().join("");

        C.split("").reverse().join("");

        let rem = 0;

        for (let i = 0; i < Math.max(L, Math.max(M, N)); i++) {

            let curr = rem;

            if (i < L)

                curr += A[i].charCodeAt(0) - 'a'.charCodeAt(0);

            if (i < M)

                curr += B[i].charCodeAt(0) - 'a'.charCodeAt(0);

            rem = Math.floor(curr / 10);

            curr %= 10;

            if (i < N && curr != C[i].charCodeAt(0) -

            'a'.charCodeAt(0)) {

                return "No";

            }

        }

        if (rem)

            return "No";

        else

            return "Yes";

    }

    let A = "acb", B = "cba", C = "cdb";

    document.write(isSumEqual(A, B, C));

    </script>

    Time Complexity: O(L+M+N)
    Auxiliary Space: O(1)

    Like Article

    Save Article

    You should use a Hamming Distance. For given two words of equal length, it is the number of positions at which the corresponding symbols are different.

    Your algorithm could look like this:

    1. Organize your words into a graph structure, where two words are connected only when Hamming distance between them equals 1, i.e. : DAMP and LAMP will be connected (h.d. is 1), but DAMP and LIMP — no (h.d. is 2).

    2. For given two words, check if there exists a path in your graph between first word and second. If so, write the path. For this you can use any of pathfinind algorithm.

    Example

    Words : DAMP, LIKE

    We are searching our graph and finds that there is a path between those words. Using, for example, Dijkstra’s algorithm we find following path:

    Path : DAMP -> LAMP -> LIMP -> LIME -> LIKE

    Home >> LeetCode >> Shuffle the Array  In this post, we will learn how to solve LeetCode’s Shuffle the Array problem and will implement its solution in Java. Shuffle the Array Given the array nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn]. Return the array in the form [x1,y1,x2,y2,…,xn,yn]. Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7]  Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. Example 2: Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] Practice this problem on LeetCode: Click Here. Shuffle the Array Java Solution Approach 1: Using a new Array. Space complexity: O(n). Java Program:  class Solution { public int [] shuffle ( int [] nums , int n ) { int [] ans = new int [ 2 * n ]; int j = 0 ; for ( int i = 0 ; i < 2 * n ; i = i + 2 ){ ans [ i ] = nums [ j ]; ans [ i + 1 ] =

    With the vast nature of the English language, it’s natural that some words have overlapping meanings, or one word may have a very similar meaning to another word. And while these overlapping words are already a lot, you might also be confused about what to call these alike meaning words.

    Terms For Two Words That Mean The Same Thing

    The word ‘synonyms’ is the most preferred way to describe two words that mean the same. ‘Synonym’ is straightforward with its meaning that when two words are synonymous, it means two words have almost or the same exact definition. Thus, making it the most appropriate word in any context.

    Synonyms

    Calling two words ‘synonymous’ is one way to indicate that two words mean the same thing. The word ‘synonym’ also follows an equal definition. However, it would be good to note that not all synonyms exactly mean the same, and there is still a most appropriate word for any context.

    For example, ‘thin’ and ‘narrow’ maybe synonymous in a way. However, it seems off to describe a person as narrow or a road as thin. In that way, even if the two words mean the same, there is still a more preferred or appropriate word in a given context. It’s best to describe the road as narrow and a person as thin or skinny. But another synonym for the two words would be slim or slender, which we can use to describe either a person or a road.

    Words Alike

    Describing two words as ‘alike’ is another way of saying that the two are synonymous. In other contexts, it could also mean that two things are similar in a way. Many also prefer to use ‘alike’ as it still means similar, but does not imply exact duplicates.

    The word ‘alike’ is also versatile as it is not only used to describe two words, but other things that are similar to each other. In the context of words or synonyms, we say ‘brave’ and ‘courageous’ are two words alike. But, we can also say ‘both of you look alike’ or ‘the two of them dress alike’ to express similarity in visuals and fashion, respectively. Thus, saying two words are alike is another way of saying they mean the same thing.

    Similar Words

    The words ‘alike’ and ‘similar’ are synonyms, and in this context, they mean the exact same thing. Like ‘alike,’ describing two words as similar means that the two words have definitions that are almost the same or in some way alike, but it does not imply exactly the same.

    The only difference between using ‘similar’ and ‘alike’ is the grammar rules or how we structure them in a sentence. We usually say that two words are alike, but when we use ‘similar,’ we say that the two are similar words. So, we say, ‘beautiful and pretty are words alike,’ but we say ‘beautiful and pretty are similar words.’ Despite this difference, the two phrases and words are still synonymous and mean the exact same.

    Likewise

    ‘Likewise’ is another synonym for ‘alike’ and ‘similar,’ and these three words mean that two words are alike or in the same way. Saying that two words are likewise is like saying that one word is also another. However, saying there are limitations in saying two words are likewise.

    Saying that two words are likewise may imply that the two words mean exactly the same. For example, saying that ‘long and tall are likewise’ is the same as saying ‘long is also tall’ and implies that the two are interchangeable. However, saying that a person is tall may not have the same meaning as saying a person is long (this may also be totally improper and inappropriate). So, it’s best to use ‘likewise’ only for words that mean the exact same.

    Parallel Words

    Describing two words as parallel is another way of saying the two are synonymous. However, there are limitations to saying this, as it implies that the two are exactly the same or their meanings are exact duplicates of one another, just like how parallel lines are.

    The limitation in using the term ‘parallel’ is that not all synonymous words may exactly be the same as another. It means that they are similar but not exactly parallel. For example, ‘happy and joyful are parallel words,’ meaning they are exactly the same in this particular context. However, you can’t say ‘nerdy and smart are parallel words’ because the two words may not mean exactly the same. Smart may be a compliment, while nerdy may come off as something offensive.

    Equal/Equivalent

    Like the word ‘parallel,’ using the word ‘equal’ or ‘equivalent’ implies that two words mean exactly the same thing. In Math, equal or equivalent terms are usually interchangeable in positions. In the same way, saying words are equal implies that they are interchangeable with each other.

    Using the term equal or equivalent may not be applicable in all cases, as not all synonyms are always interchangeable in all contexts. For example, the word ugly and horrible may be equals or equivalents when describing a person’s looks. However, ugly is not an appropriate equivalent of horrible when describing the taste of a food.

    Describing two words are the ‘same’ is a graver version of saying two words are ‘similar’ or ‘alike.’ Unlike the two latter words, the word ‘same’ emphasizes or implies that the two given words are exactly the same. It’s another way of saying the two are equal or parallel.

    However, describing something as ‘the same’ is not always applicable and varies depending on the context. In one context where two words are interchangeable, ‘Dirty and filthy are the same’ for example, here, ‘same’ works. However, there are also synonymous and similar words that aren’t exactly the same and are not interchangeable with each other.

    Identical Words

    Describing two words as ‘identical’ strongly implies that the two are exactly the same. A simple analogy for this is that, identical twins are usually twins that are almost exact duplicates of each other. In the same way, identical words imply they are duplicates or totally the same.

    However, not all words are always the same. So, using ‘identical’ actually needs more caution, especially since it may give off a wrong meaning that two words are precisely the same but may not be the case all the time. For example saying ‘charm and beauty are identical words’ may be true for some individuals or in a given context, but it may not be the case for others or other contexts.

    Interchangeable Words

    Saying two words are interchangeable directly means that the words are synonymous and interchangeable. It simply means that you could use both words in the given context. Given this, though, we only use it for two words that are precisely the same and appropriate for the said context.

    For example, saying that ‘beautiful and pretty are interchangeable’ directly implies that you can use either of the two words in your sentence or the context you want to use it. However, we only use ‘interchangeable’ for two words that are precisely the same and interchangeable with each other, without any change of meaning.

    Redundant

    We say words are redundant when they are put in the same sentence but mean the same thing. ‘Redundant’ actually means exceeding what is necessary, meaning there are more than the needed words to describe what you want to do so. In the same way, one can redact redundant words.

    An example of redundancy is saying, ‘she was shy and bashful during the first day.’ Here, ‘shy’ and ‘bashful’ may be redundant as they mean the same thing. While keeping the sentence as is works also, one may also remove redundancy by keeping only one of the two words, and discarding or redacting the other.

    Tautologous

    Saying a phrase is tautologous is another way of saying that it is redundant, implying that there is an unneeded repetition of ideas in a sentence. Though these words are usually redundant, there are different tautologous phrases that we often use in everyday conversations.

    An example of a tautologous phrase would be ‘adequate enough.’ Essentially, adequate and enough have the same meaning of being as much as required or needed. So, putting ‘adequate’ and ‘enough’ together may seem redundant, but many speakers still use it in various contexts and daily conversations.

    Pleonasm

    Pleonasm is more of a linguistic style and expression. It is using redundant phrases and words, more words than necessary, to emphasize meaning and add more style. The word pleonasm, in it’s Latin origin, already means to be excessive, and so pleonasm also means being excessive in redundant phrases.

    An example of pleonasm is saying ‘burning fire.’ Saying ‘burning’ and ‘fire’ becomes redundant, as saying ‘fire’ in itself already means it is burning. Another would be the phrase ‘hear with my own ears,’ which becomes redundant as the ears is the only way one can hear.

    You may also like: 10 Terms For Two Words That Contradicts Each Other

    martin lassen dam grammarhow

    Martin holds a Master’s degree in Finance and International Business. He has six years of experience in professional communication with clients, executives, and colleagues. Furthermore, he has teaching experience from Aarhus University. Martin has been featured as an expert in communication and teaching on Forbes and Shopify. Read more about Martin here.

    Javascript Online Compiler

    Write, Run & Share Javascript code online using OneCompiler’s JS online compiler for free. It’s one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler’s Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

    About Javascript

    Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

    Key Features

    • Open-source
    • Just-in-time compiled language
    • Embedded along with HTML and makes web pages alive
    • Originally named as LiveScript.
    • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

    Syntax help

    variable declaration

    Keyword Description Scope
    var Var is used to declare variables(old way of declaring variables) Function or global scope
    let let is also used to declare variables(new way) Global or block Scope
    const const is used to declare const values. Once the value is assigned, it can not be modified Global or block Scope

    Backtick Strings

    Interpolation

    let greetings = `Hello ${name}`

    Multi line Strings

    const msg = `
    hello
    world!
    `

    Arrays

    An array is a collection of items or values.

    Syntax:

    let arrayName = [value1, value2,..etc];
    // or
    let arrayName = new Array("value1","value2",..etc);

    Example:

    let mobiles = ["iPhone", "Samsung", "Pixel"];
    
    // accessing an array
    console.log(mobiles[0]);
    
    // changing an array element
    mobiles[3] = "Nokia";

    Arrow functions

    Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
    Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

    Syntax:

    () => expression

    Example:

    const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                        .map(ele => ele ** 2);
    console.log(squaresOfEvenNumbers);

    De-structuring

    Arrays

    let [firstName, lastName] = ['Foo', 'Bar']

    Objects

    let {firstName, lastName} = {
      firstName: 'Foo',
      lastName: 'Bar'
    }

    rest(…) operator

     const {
        title,
        firstName,
        lastName,
        ...rest
      } = record;

    Spread(…) operator

    //Object spread
    const post = {
      ...options,
      type: "new"
    }
    //array spread
    const users = [
      ...adminUsers,
      ...normalUsers
    ]

    Functions

    function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
      console.log(`Hello ${name}!`);
    }
     
    greet() // Hello Foo
    greet({ name: 'Bar' }) // Hi Bar

    Loops

    1. If:

    IF is used to execute a block of code based on a condition.

    Syntax

    if(condition){
        // code
    }

    2. If-Else:

    Else part is used to execute the block of code when the condition fails.

    Syntax

    if(condition){
        // code
    } else {
        // code
    }

    3. Switch:

    Switch is used to replace nested If-Else statements.

    Syntax

    switch(condition){
        case 'value1' :
            //code
            [break;]
        case 'value2' :
            //code
            [break;]
        .......
        default :
            //code
            [break;]
    }

    4. For

    For loop is used to iterate a set of statements based on a condition.

    for(Initialization; Condition; Increment/decrement){  
    //code  
    } 

    5. While

    While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

    while (condition) {  
      // code 
    }  

    6. Do-While

    Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

    do {  
      // code 
    } while (condition); 

    Classes

    ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

    Syntax:

    class className {
      constructor() { ... } //Mandatory Class method
      method1() { ... }
      method2() { ... }
      ...
    }

    Example:

    class Mobile {
      constructor(model) {
        this.name = model;
      }
    }
    
    mbl = new Mobile("iPhone");

    Самый быстрый алгоритм — сопоставить каждый из 26 английских символов с уникальным простым числом. Затем вычислите произведение строки. По основной теореме арифметики 2 строки являются анаграммами тогда и только тогда, когда их произведения одинаковы.

    SeriousBusiness
    08 июнь 2013, в 23:32

    Поделиться

    Два слова являются анаграммами друг друга, если они содержат одинаковое количество символов и одинаковые символы. Вам нужно только отсортировать символы в лексикографическом порядке и определить, равны ли все символы в одной строке и в том же порядке, что и все символы в другой строке.

    Вот пример кода. Посмотрите на Arrays в API, чтобы понять, что здесь происходит.

    public boolean isAnagram(String firstWord, String secondWord) {
         char[] word1 = firstWord.replaceAll("[\s]", "").toCharArray();
         char[] word2 = secondWord.replaceAll("[\s]", "").toCharArray();
         Arrays.sort(word1);
         Arrays.sort(word2);
         return Arrays.equals(word1, word2);
    }
    

    Makoto
    23 фев. 2013, в 21:35

    Поделиться

    Если вы сортируете либо массив, решение становится O (n log n). но если вы используете хэш-карту, это O (n). протестированы и работают.

    char[] word1 = "test".toCharArray();
    char[] word2 = "tes".toCharArray();
    
    Map<Character, Integer> lettersInWord1 = new HashMap<Character, Integer>();
    
    for (char c : word1) {
        int count = 1;
        if (lettersInWord1.containsKey(c)) {
            count = lettersInWord1.get(c) + 1;
        }
        lettersInWord1.put(c, count);
    }
    
    for (char c : word2) {
        int count = -1;
        if (lettersInWord1.containsKey(c)) {
            count = lettersInWord1.get(c) - 1;
        }
        lettersInWord1.put(c, count);
    }
    
    for (char c : lettersInWord1.keySet()) {
        if (lettersInWord1.get(c) != 0) {
            return false;
        }
    }
    
    return true;
    

    jb.
    23 фев. 2013, в 22:15

    Поделиться

    Здесь простое быстрое решение O (n) без использования сортировки или множественных циклов или хеш-карт. Мы увеличиваем счет каждого символа в первом массиве и уменьшаем счетчик каждого символа во втором массиве. Если результирующий массив counts заполнен нулями, строки являются анаграммами. Может быть расширен, чтобы включить другие символы, увеличив размер массива counts.

    class AnagramsFaster{
    
        private static boolean compare(String a, String b){
            char[] aArr = a.toLowerCase().toCharArray(), bArr = b.toLowerCase().toCharArray();
            if (aArr.length != bArr.length)
                return false;
            int[] counts = new int[26]; // An array to hold the number of occurrences of each character
            for (int i = 0; i < aArr.length; i++){
                counts[aArr[i]-97]++;  // Increment the count of the character at i
                counts[bArr[i]-97]--;  // Decrement the count of the character at i
            }
            // If the strings are anagrams, the counts array will be full of zeros
            for (int i = 0; i<26; i++)
                if (counts[i] != 0)
                    return false;
            return true;
        }
    
        public static void main(String[] args){
            System.out.println(compare(args[0], args[1]));
        }
    }
    

    Aswin
    02 март 2015, в 00:41

    Поделиться

    Множество людей представили решения, но я просто хочу поговорить об алгоритмической сложности некоторых общих подходов:

    • Простым «сортировка символов с использованием Arrays.sort()» будет O(N log N).

    • Если вы используете сортировку radix, которая сводится к O(N) с пространством O(M), где M — количество различных символов в алфавите. (Это 26 на английском языке… но теоретически мы должны рассматривать многоязычные анаграммы.)

    • «Считайте символы», используя массив счетчиков, также O(N)… и быстрее, чем сортировка по методу radix, потому что вам не нужно восстанавливать отсортированную строку. Использование пространства будет O(M).

    • «Считать символы» с помощью словаря, hashmap, treemap или эквивалента будет медленнее, чем подход массива, если только алфавит не огромен.

    • В худшем случае, к сожалению, O(N^2) изящный подход «из простых чисел». Это потому, что для достаточно длинных слов или фраз продукт простых чисел не будет вписываться в long, Это означает, что вам нужно использовать BigInteger, а N раз умножение a BigInteger на небольшую константу — O(N^2).

      Для гипотетического большого алфавита масштабный коэффициент будет большим. Использование наихудшего пространства для хранения произведения простых чисел как BigInteger (я думаю) O(N*logM).

    • Основанный на A hashcode подход обычно O(N), если слова не являются анаграммами. Если хэш-коды равны, то вам все равно нужно сделать правильный тест анаграммы. Таким образом, это не полное решение.

    Stephen C
    27 сен. 2014, в 04:41

    Поделиться

    O (n) без какой-либо сортировки и использования только одной карты.

    public boolean isAnagram(String leftString, String rightString) {
      if (leftString == null || rightString == null) {
        return false;
      } else if (leftString.length() != rightString.length()) {
        return false;
      }
    
      Map<Character, Integer> occurrencesMap = new HashMap<>();
    
      for(int i = 0; i < leftString.length(); i++){
        char charFromLeft = leftString.charAt(i);
        int nrOfCharsInLeft = occurrencesMap.containsKey(charFromLeft) ? occurrencesMap.get(charFromLeft) : 0;
        occurrencesMap.put(charFromLeft, ++nrOfCharsInLeft);
        char charFromRight = rightString.charAt(i);
        int nrOfCharsInRight = occurrencesMap.containsKey(charFromRight) ? occurrencesMap.get(charFromRight) : 0;
        occurrencesMap.put(charFromRight, --nrOfCharsInRight);
      }
    
      for(int occurrencesNr : occurrencesMap.values()){
        if(occurrencesNr != 0){
          return false;
        }
      }
    
      return true;
    }
    

    и менее общее решение, но немного быстрее. Здесь вы должны поместить свой алфавит:

    public boolean isAnagram(String leftString, String rightString) {
      if (leftString == null || rightString == null) {
        return false;
      } else if (leftString.length() != rightString.length()) {
        return false;
      }
    
      char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
      Map<Character, Integer> occurrencesMap = new HashMap<>();
      for (char l : letters) {
        occurrencesMap.put(l, 0);
      }
    
      for(int i = 0; i < leftString.length(); i++){
        char charFromLeft = leftString.charAt(i);
        Integer nrOfCharsInLeft = occurrencesMap.get(charFromLeft);
        occurrencesMap.put(charFromLeft, ++nrOfCharsInLeft);
        char charFromRight = rightString.charAt(i);
        Integer nrOfCharsInRight = occurrencesMap.get(charFromRight);
        occurrencesMap.put(charFromRight, --nrOfCharsInRight);
      }
    
      for(Integer occurrencesNr : occurrencesMap.values()){
        if(occurrencesNr != 0){
          return false;
        }
      }
    
      return true;
    }
    

    goroncy
    04 фев. 2014, в 13:25

    Поделиться

    Мы ходим по двум строкам равной длины и отслеживаем различия между ними. Нам все равно, каковы различия, мы просто хотим знать, имеют ли они одинаковые символы или нет. Мы можем сделать это в O (n/2) без какой-либо последующей обработки (или много простых чисел).

    public class TestAnagram {
      public static boolean isAnagram(String first, String second) {
        String positive = first.toLowerCase();
        String negative = second.toLowerCase();
    
        if (positive.length() != negative.length()) {
          return false;
        }
    
        int[] counts = new int[26];
    
        int diff = 0;
    
        for (int i = 0; i < positive.length(); i++) {
          int pos = (int) positive.charAt(i) - 97; // convert the char into an array index
          if (counts[pos] >= 0) { // the other string doesn't have this
            diff++; // an increase in differences
          } else { // it does have it
            diff--; // a decrease in differences
          }
          counts[pos]++; // track it
    
          int neg = (int) negative.charAt(i) - 97;
          if (counts[neg] <= 0) { // the other string doesn't have this
            diff++; // an increase in differences
          } else { // it does have it
            diff--; // a decrease in differences
          }
          counts[neg]--; // track it
        }
    
        return diff == 0;
      }
    
      public static void main(String[] args) {
        System.out.println(isAnagram("zMarry", "zArmry")); // true
        System.out.println(isAnagram("basiparachromatin", "marsipobranchiata")); // true
        System.out.println(isAnagram("hydroxydeoxycorticosterones", "hydroxydesoxycorticosterone")); // true
        System.out.println(isAnagram("hydroxydeoxycorticosterones", "hydroxydesoxycorticosterons")); // false
        System.out.println(isAnagram("zArmcy", "zArmry")); // false
      }
    }
    

    Да, этот код зависит от набора символов ASCII английского алфавита с нижним регистром, но его не следует изменять на другие языки. Вы всегда можете использовать Map [Character, Int] для отслеживания одной и той же информации, это будет только медленнее.

    Jeff Thomas
    30 янв. 2014, в 03:27

    Поделиться

    Здесь много сложных ответов. Основываясь на принятом ответе и комментарий, в котором упоминается проблема «ac» — «bb», предполагающая A = 1 B = 2 C = 3, мы могли бы просто использовать квадрат каждого целого числа, представляющего char, и решить проблему:

    public boolean anagram(String s, String t) {
        if(s.length() != t.length())
            return false;
    
        int value = 0;
        for(int i = 0; i < s.length(); i++){
            value += ((int)s.charAt(i))^2;
            value -= ((int)t.charAt(i))^2;
        }
        return value == 0;
    }
    

    chakming
    15 июль 2015, в 10:22

    Поделиться

    Я разработчик С++, а код ниже — на С++. Я считаю, что самый быстрый и простой способ сделать это будет следующим:

    Создайте вектор ints размером 26, со всеми слотами, инициализированными до 0, и поместите каждый символ строки в соответствующую позицию в векторе. Помните, что вектор находится в алфавитном порядке, поэтому, если первая буква в строке равна z, она войдет в myvector [26]. Примечание. Это можно сделать с использованием символов ASCII, поэтому ваш код будет выглядеть примерно так:

    string s = zadg;
    for(int i =0; i < s.size(); ++i){
        myvector[s[i] - 'a'] = myvector['s[i] - 'a'] + 1;
    } 
    

    Таким образом, для вставки всех элементов потребуется время O (n), так как вы проходите только один раз. Теперь вы можете сделать то же самое для второй строки, и это тоже займет время O (n). Затем вы можете сравнить два вектора, проверив, совпадают ли счетчики в каждом слоте. Если они есть, это означает, что у вас было одинаковое количество символов EACH в обеих строках и, следовательно, они являются анаграммами. Сравнение двух векторов также должно занимать время O (n), поскольку вы только проходите через него один раз.

    Примечание. Код работает только для одного слова символов. Если у вас есть пробелы, цифры и символы, вы можете просто создать вектор размером 96 (символы ASCII 32-127) и вместо того, чтобы говорить — «a», вы бы сказали — «», поскольку символ пробела является первым в Список символов ASCII.

    Надеюсь, это поможет. Если я где-то ошибся, оставьте комментарий.

    muneebahmad
    15 фев. 2014, в 21:06

    Поделиться

        /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package Algorithms;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import javax.swing.JOptionPane;
    
    /**
     *
     * @author Mokhtar
     */
    public class Anagrams {
    
        //Write aprogram to check if two words are anagrams
        public static void main(String[] args) {
            Anagrams an=new Anagrams();
            ArrayList<String> l=new ArrayList<String>();
            String result=JOptionPane.showInputDialog("How many words to test anagrams");
            if(Integer.parseInt(result) >1)
            {    
                for(int i=0;i<Integer.parseInt(result);i++)
                {
    
                    String word=JOptionPane.showInputDialog("Enter word #"+i);
                    l.add(word);   
                }
                System.out.println(an.isanagrams(l));
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Can not be tested, nYou can test two words or more");
            }
    
        }
    
        private static String sortString( String w )
        {
            char[] ch = w.toCharArray();
            Arrays.sort(ch);
            return new String(ch);
        }
    
        public boolean isanagrams(ArrayList<String> l)
        {
            boolean isanagrams=true; 
            ArrayList<String> anagrams = null;
            HashMap<String, ArrayList<String>> map =  new HashMap<String, ArrayList<String>>();
            for(int i=0;i<l.size();i++)
                {
            String word = l.get(i);
            String sortedWord = sortString(word);
                anagrams = map.get( sortedWord );
            if( anagrams == null ) anagrams = new ArrayList<String>();
            anagrams.add(word);
            map.put(sortedWord, anagrams);
                }
    
                for(int h=0;h<l.size();h++)
                {
                    if(!anagrams.contains(l.get(h)))
                    {
                        isanagrams=false;
                        break;
                    }
                }
    
                return isanagrams;
            //}
            }
    
    }
    

    Mokhtar Kalmoush
    08 дек. 2013, в 03:53

    Поделиться

    Используя больше памяти (HashMap из не более N/2 элементов), нам не нужно сортировать строки.

    public static boolean areAnagrams(String one, String two) {
        if (one.length() == two.length()) {
            String s0 = one.toLowerCase();
            String s1 = two.toLowerCase();
            HashMap<Character, Integer> chars = new HashMap<Character, Integer>(one.length());
            Integer count;
            for (char c : s0.toCharArray()) {
                count = chars.get(c);
                count = Integer.valueOf(count != null ? count + 1 : 1);
                chars.put(c, count);
            }
            for (char c : s1.toCharArray()) {
                count = chars.get(c);
                if (count == null) {
                    return false;
                } else {
                    count--;
                    chars.put(c, count);
                }
            }
            for (Integer i : chars.values()) {
                if (i != 0) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }
    

    Эта функция фактически выполняется в O (N)… вместо O (NlogN) для решения, которое сортирует строки. Если бы я предполагал, что вы собираетесь использовать только буквенные символы, я могу использовать только массив из 26 int (от a до z без акцентов или украшений) вместо хэш-карты.

    Если мы определим, что:
    N = | один | + | два |
    мы делаем одну итерацию по N (один раз над одним, чтобы увеличить счетчики, и один раз, чтобы уменьшить их на два).
    Затем, чтобы проверить итоговые значения, мы перебираем в mose N/2.

    Другие описанные алгоритмы имеют одно преимущество: они не используют дополнительную память, предполагая, что Arrays.sort использует inplace версии QuickSort или сортировку слияния. Но поскольку мы говорим об анаграммах, я предполагаю, что мы говорим о человеческих языках, поэтому слова не должны быть достаточно длинными, чтобы давать проблемы с памятью.

    ɭɘ ɖɵʊɒɼɖ 江戸
    07 авг. 2013, в 11:19

    Поделиться

    Спасибо за указание сделать комментарий, комментируя, я обнаружил, что была неправильная логика. Я исправил логику и добавил комментарий для каждой части кода.

    // Time complexity: O(N) where N is number of character in String
    // Required space :constant space.
    // will work for string that contains ASCII chars
    
    private static boolean isAnagram(String s1, String s2) {
    
        // if length of both string are not equal then they are not anagram of each other 
        if(s1.length() != s2.length())return false;
    
        // array to store the presence of a character with number of occurrences.   
        int []seen = new int[256];
    
        // initialize the array with zero. Do not need to initialize specifically  since by default element will initialized by 0.
        // Added this is just increase the readability of the code. 
        Arrays.fill(seen, 0);
    
        // convert each string to lower case if you want to make ABC and aBC as anagram, other wise no need to change the case.  
        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();
    
        //  iterate through the first string and count the occurrences of each character
        for(int i =0; i < s1.length(); i++){
            seen[s1.charAt(i)] = seen[s1.charAt(i)] +1;
        }
    
        // iterate through second string and if any char has 0 occurrence then return false, it mean some char in s2 is there that is not present in s1.
        // other wise reduce the occurrences by one every time .
        for(int i =0; i < s2.length(); i++){
            if(seen[s2.charAt(i)] ==0)return false;
            seen[s2.charAt(i)] = seen[s2.charAt(i)]-1;
        }
    
        // now if both string have same occurrence of each character then the seen array must contains all element as zero. if any one has non zero element return false mean there are 
        // some character that either does not appear in one of the string or/and mismatch in occurrences 
        for(int i = 0; i < 256; i++){
            if(seen[i] != 0)return false;
        }
        return true;
    }
    

    Kuldeep Singh
    12 июнь 2016, в 09:37

    Поделиться

    Вот мое решение. Сначала взорвите строки в массивы char, затем отсортируйте их, а затем сравните, если они равны или нет. Я предполагаю, что временная сложность этого кода равна O (a + b).if a = b, мы можем сказать O (2A)

    public boolean isAnagram(String s1, String s2) {
    
            StringBuilder sb1 = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            if (s1.length() != s2.length())
                return false;
    
            char arr1[] = s1.toCharArray();
            char arr2[] = s2.toCharArray();
            Arrays.sort(arr1);
            Arrays.sort(arr2);
    
    
    
            for (char c : arr1) {
                sb1.append(c);
            }
    
            for (char c : arr2) {
                sb2.append(c);
            }
    
            System.out.println(sb1.toString());
            System.out.println(sb2.toString());
    
            if (sb1.toString().equals(sb2.toString()))
                return true;
            else
                return false;
    
        }
    

    Türkmen Mustafa Demirci
    18 окт. 2017, в 09:03

    Поделиться

    IMHO, наиболее эффективное решение было предоставлено @Siguza, я расширил его, чтобы охватить строки с пространством, например: «Уильям Шекспир», «Я слабый спелер», «Мастер школы», «Класс»

    public int getAnagramScore(String word, String anagram) {
    
            if (word == null || anagram == null) {
                throw new NullPointerException("Both, word and anagram, must be non-null");
            }
    
            char[] wordArray = word.trim().toLowerCase().toCharArray();
            char[] anagramArray = anagram.trim().toLowerCase().toCharArray();
    
            int[] alphabetCountArray = new int[26];
    
            int reference = 'a';
    
            for (int i = 0; i < wordArray.length; i++) {
                if (!Character.isWhitespace(wordArray[i])) {
                    alphabetCountArray[wordArray[i] - reference]++;
                }
            }
            for (int i = 0; i < anagramArray.length; i++) {
                if (!Character.isWhitespace(anagramArray[i])) {
                    alphabetCountArray[anagramArray[i] - reference]--;
                }
            }
    
            for (int i = 0; i < 26; i++)
                if (alphabetCountArray[i] != 0)
                    return 0;
    
            return word.length();
    
        }
    

    Kaliyug Antagonist
    17 сен. 2017, в 12:19

    Поделиться

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.TreeMap;
    /**
     * Check if Anagram by Prime Number Logic
     * @author Pallav
     *
     */
    public class Anagram {
        public static void main(String args[]) {
            System.out.println(isAnagram(args[0].toUpperCase(),
                    args[1].toUpperCase()));
        }
    /**
     * 
     * @param word : The String 1
     * @param anagram_word : The String 2 with which Anagram to be verified
     * @return true or false based on Anagram
     */
        public static Boolean isAnagram(String word, String anagram_word) {
            //If length is different return false
            if (word.length() != anagram_word.length()) {
                return false;
            }
            char[] words_char = word.toCharArray();//Get the Char Array of First String
            char[] anagram_word_char = anagram_word.toCharArray();//Get the Char Array of Second String
            int words_char_num = 1;//Initialize Multiplication Factor to 1
            int anagram_word_num = 1;//Initialize Multiplication Factor to 1 for String 2
            Map<Character, Integer> wordPrimeMap = wordPrimeMap();//Get the Prime numbers Mapped to each alphabets in English
            for (int i = 0; i < words_char.length; i++) {
                words_char_num *= wordPrimeMap.get(words_char[i]);//get Multiplication value for String 1
            }
            for (int i = 0; i < anagram_word_char.length; i++) {
                anagram_word_num *= wordPrimeMap.get(anagram_word_char[i]);//get Multiplication value for String 2
            }
    
            return anagram_word_num == words_char_num;
        }
    /**
     * Get the Prime numbers Mapped to each alphabets in English
     * @return
     */
        public static Map<Character, Integer> wordPrimeMap() {
            List<Integer> primes = primes(26);
            int k = 65;
            Map<Character, Integer> map = new TreeMap<Character, Integer>();
            for (int i = 0; i < primes.size(); i++) {
                Character character = (char) k;
                map.put(character, primes.get(i));
                k++;
            }
            // System.out.println(map);
            return map;
        }
    /**
     * get first N prime Numbers where Number is greater than 2
     * @param N : Number of Prime Numbers
     * @return
     */
        public static List<Integer> primes(Integer N) {
            List<Integer> primes = new ArrayList<Integer>();
            primes.add(2);
            primes.add(3);
    
            int n = 5;
            int k = 0;
            do {
                boolean is_prime = true;
                for (int i = 2; i <= Math.sqrt(n); i++) {
                    if (n % i == 0) {
                        is_prime = false;
                        break;
                    }
                }
    
                if (is_prime == true) {
                    primes.add(n);
    
                }
                n++;
                // System.out.println(k);
            } while (primes.size() < N);
    
            // }
    
            return primes;
        }
    
    }
    

    Kumar Pallav
    04 сен. 2016, в 17:41

    Поделиться

    Пока все предлагаемые решения работают с отдельными элементами char, а не с кодовыми точками. Я хотел бы предложить два решения для правильной обработки суррогатных пар (это символы from U + 10000 до U + 10FFFF, состоящий из двух элементов char).

    1) Однострочное решение O (n logn), в котором используется Java 8 CharSequence.codePoints() поток:

    static boolean areAnagrams(CharSequence a, CharSequence b) {
        return Arrays.equals(a.codePoints().sorted().toArray(),
                             b.codePoints().sorted().toArray());
    }
    

    2) Менее элегантное решение O (n) (на самом деле оно будет быстрее только для длинных строк с небольшими шансами быть анаграммами):

    static boolean areAnagrams(CharSequence a, CharSequence b) {
        int len = a.length();
        if (len != b.length())
            return false;
    
        // collect codepoint occurrences in "a"
        Map<Integer, Integer> ocr = new HashMap<>(64);
        a.codePoints().forEach(c -> ocr.merge(c, 1, Integer::sum));
    
        // for each codepoint in "b", look for matching occurrence
        for (int i = 0, c = 0; i < len; i += Character.charCount(c)) {
            int cc = ocr.getOrDefault((c = Character.codePointAt(b, i)), 0);
            if (cc == 0)                        
                return false;            
            ocr.put(c, cc - 1);
        }
        return true;
    }
    

    Alex Salauyou
    25 март 2016, в 10:51

    Поделиться

    Как математик может подумать о проблеме до написания кода:

    • Отношение «являются анаграммами» между строками — это отношение эквивалентности, поэтому разбивает набор всех строк на классы эквивалентности.
    • Предположим, что у нас было правило выбирать представитель (crib) из каждого класса, тогда легко проверить, совпадают ли два класса, сравнивая их представителей.
    • Очевидным представителем для набора строк является «наименьший < элемент по лексикографическому порядку«, который легко вычислить из любого элемента путем сортировки. Например, представителем класса анаграммы, содержащего «шляпу», является «aht».

    В вашем примере «школьный учитель» и «theclassroom» являются анаграммами, потому что они оба находятся в классе анаграмм с кроваткой «acehlmoorsst».

    В псевдокоде:

    >>> def crib(word):
    ...     return sorted(word)
    ...
    >>> crib("schoolmaster") == crib("theclassroom")
    True
    

    Colonel Panic
    29 июль 2015, в 16:18

    Поделиться

    Подобный ответ, возможно, был опубликован на С++, здесь он снова находится на Java. Обратите внимание, что самым элегантным способом было бы использовать Trie для хранения символов в отсортированном порядке, однако, это более сложное решение. Один из способов — использовать hashset для хранения всех слов, которые мы сравниваем, а затем сравниваем их по одному. Чтобы сравнить их, создайте массив символов с индексом, представляющим значение ANCII символов (с использованием нормализатора, т.е. Значение ANCII «a» равно 97) и значение, представляющее количество совпадений этого символа. Это будет работать в O (n) времени и использовать O (m * z) пространство, где m — размер currentWord, а z — размер для сохраненногоWord, для которого мы создаем Char [].

    public static boolean makeAnagram(String currentWord, String storedWord){
        if(currentWord.length() != storedWord.length()) return false;//words must be same length
        Integer[] currentWordChars = new Integer[totalAlphabets];
        Integer[] storedWordChars = new Integer[totalAlphabets];
        //create a temp Arrays to compare the words
        storeWordCharacterInArray(currentWordChars, currentWord);
        storeWordCharacterInArray(storedWordChars, storedWord);
        for(int i = 0; i < totalAlphabets; i++){
            //compare the new word to the current charList to see if anagram is possible
            if(currentWordChars[i] != storedWordChars[i]) return false;
        }
        return true;//and store this word in the HashSet of word in the Heap
    }
    //for each word store its characters
    public static void storeWordCharacterInArray(Integer[] characterList, String word){
        char[] charCheck = word.toCharArray();
        for(char c: charCheck){
            Character cc = c;
            int index = cc.charValue()-indexNormalizer;
            characterList[index] += 1;
        }
    }
    

    ak_2050
    20 апр. 2014, в 14:46

    Поделиться

    Я столкнулся с этой концепцией HashMap в Anagrams Problem, которая очень интересна.

    Вопрос: проверьте, являются ли два слова Anagrams.

    Решение:

    import java.util.HashMap;
    import java.util.Map;
    
    public class Anagram2 {
        public static void main(String[] args) {
            String a = "protijayiGini";
            String b = "jayiprotiiGin";
            System.out.println(checkanagrams(a,b));
        }
        static boolean checkanagrams(String a  , String  b) {
            Map<Character,Integer> map = new HashMap<>();
            for (int i = 0; i < a.length(); i++) {
                char ch = a.charAt(i);
                if (map.containsKey(ch)) {
                    map.put(ch, map.get(ch) +1 );
                } else {
                    map.put(ch, 1);
                }
            }
            //chars sin hashmap
            for(int i = 0 ; i < b.length(); i++) {
                char ch = b.charAt(i);
                if (!map.containsKey(ch)) {
                    return false;
                } else if(map.containsKey(ch)) {
                    Integer frequencyOfCharacter = map.get(ch);
                    if(frequencyOfCharacter == 0) {
                        return false;
                    } else {
                        map.put(ch, --frequencyOfCharacter);
                    }
                }
           }
           return true;
        }
    }
    

    Soudipta Dutta
    19 март 2018, в 09:42

    Поделиться

    private static boolean checkAnagram(String s1, String s2) {
       if (s1 == null || s2 == null) {
           return false;
       } else if (s1.length() != s2.length()) {
           return false;
       }
       char[] a1 = s1.toCharArray();
       char[] a2 = s2.toCharArray();
       int length = s2.length();
       int s1Count = 0;
       int s2Count = 0;
       for (int i = 0; i < length; i++) {
           s1Count+=a1[i];
           s2Count+=a2[i];
       }
       return s2Count == s1Count ? true : false;
    }
    

    Amardeep Kumar
    21 июль 2017, в 13:04

    Поделиться

    Простое решение:

        public class Java_Anagrams {
    
      static boolean isAnagram(String a, String b) {
           char[] aArr = a.toUpperCase().trim().toCharArray();
           char[] bArr = b.toUpperCase().trim().toCharArray();
            if (aArr.length != bArr.length)
                return false;
            Arrays.sort(aArr);
            Arrays.sort(bArr);
            if(String.valueOf(aArr).equals(String.valueOf(bArr))){
                return true;
            }
            return false;
        }
        public static void main(String[] args) {
            String a = "Hello";
            String b =  "holle";
            boolean ret = isAnagram(a, b);
            System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
        }
    
    }
    

    Suresh
    05 янв. 2017, в 02:42

    Поделиться

    Вот еще один подход, использующий HashMap в Java

    public static boolean isAnagram(String first, String second) {
        if (first == null || second == null) {
            return false;
        }
        if (first.length() != second.length()) {
            return false;
        }
        return doCheckAnagramUsingHashMap(first.toLowerCase(), second.toLowerCase());
    }
    
    private static boolean doCheckAnagramUsingHashMap(final String first, final String second) {
        Map<Character, Integer> counter = populateMap(first, second);
        return validateMap(counter);
    }
    
    private static boolean validateMap(Map<Character, Integer> counter) {
        for (int val : counter.values()) {
            if (val != 0) {
                return false;
            }
        }
        return true;
    }
    

    Вот тестовый пример

    @Test
    public void anagramTest() {
        assertTrue(StringUtil.isAnagram("keep" , "PeeK"));
        assertFalse(StringUtil.isAnagram("Hello", "hell"));
        assertTrue(StringUtil.isAnagram("SiLeNt caT", "LisTen cat"));       
    }
    

    craftsmannadeem
    17 фев. 2016, в 11:47

    Поделиться

    Я увидел, что никто не использовал подход «hashcode» для поиска анаграмм. Я обнаружил, что мой подход мало чем отличается от описанных выше подходов, поэтому он решил поделиться им. Я написал код ниже, чтобы найти анаграммы, которые работают в O (n).

    /**
     * This class performs the logic of finding anagrams
     * @author ripudam
     *
     */
    public class AnagramTest {
    
        public static boolean isAnagram(final String word1, final String word2) {
    
                if (word1 == null || word2 == null || word1.length() != word2.length()) {
                     return false;
                }
    
                if (word1.equals(word2)) {
                    return true;
                }
    
                final AnagramWrapper word1Obj = new AnagramWrapper(word1);
                final AnagramWrapper word2Obj = new AnagramWrapper(word2);
    
                if (word1Obj.equals(word2Obj)) {
                    return true;
                }
    
                return false;
            }
    
            /*
             * Inner class to wrap the string received for anagram check to find the
             * hash
             */
            static class AnagramWrapper {
                String word;
    
                public AnagramWrapper(final String word) {
                    this.word = word;
                }
    
                @Override
                public boolean equals(final Object obj) {
    
                    return hashCode() == obj.hashCode();
                }
    
                @Override
                public int hashCode() {
                    final char[] array = word.toCharArray();
                    int hashcode = 0;
                    for (final char c : array) {
                        hashcode = hashcode + (c * c);
                    }
                    return hashcode;
                }
             }
        }
    

    Ripu Daman
    25 сен. 2014, в 21:37

    Поделиться

    Извините, решение находится на С#, но я думаю, что различные элементы, используемые для решения, являются довольно интуитивными. Небольшая настройка, требуемая для переносимых слов, но для нормальных слов она должна работать нормально.

        internal bool isAnagram(string input1,string input2)
        {
            Dictionary<char, int> outChars = AddToDict(input2.ToLower().Replace(" ", ""));
            input1 = input1.ToLower().Replace(" ","");
            foreach(char c in input1)
            {
                if (outChars.ContainsKey(c))
                {
                    if (outChars[c] > 1)
                        outChars[c] -= 1;
                    else
                        outChars.Remove(c);
                }
            }
            return outChars.Count == 0;
        }
    
        private Dictionary<char, int> AddToDict(string input)
        {
            Dictionary<char, int> inputChars = new Dictionary<char, int>();
            foreach(char c in input)
            {
                if(inputChars.ContainsKey(c))
                {
                    inputChars[c] += 1;
                }
                else
                {
                    inputChars.Add(c, 1);
                }     
            }
            return inputChars;
        }
    

    Sai
    15 июнь 2014, в 14:17

    Поделиться

    Простой способ выяснить, является ли testString анаграммой baseString.

    private static boolean isAnagram(String baseString, String testString){
        //Assume that there are no empty spaces in either string.
    
        if(baseString.length() != testString.length()){
            System.out.println("The 2 given words cannot be anagram since their lengths are different");
            return false;
        }
        else{
            if(baseString.length() == testString.length()){
                if(baseString.equalsIgnoreCase(testString)){
                    System.out.println("The 2 given words are anagram since they are identical.");
                    return true;
                }
                else{
                    List<Character> list = new ArrayList<>();
    
                    for(Character ch : baseString.toLowerCase().toCharArray()){
                        list.add(ch);
                    }
                    System.out.println("List is : "+ list);
    
                    for(Character ch : testString.toLowerCase().toCharArray()){
                        if(list.contains(ch)){
                            list.remove(ch);
                        }
                    }
    
                    if(list.isEmpty()){
                        System.out.println("The 2 words are anagrams");
                        return true;
                    }
                }
            }
        }
        return false;
    }
    

    Anshul Abhinav
    13 май 2014, в 11:57

    Поделиться

    Сортировка не самая лучшая. Требуется O (n) пространство и O (nlogn) время. Вместо этого создайте хэш-карту символов и подсчитайте их (увеличивайте символы, которые появляются в первой строке, и уменьшайте символы, которые появляются во второй строке). Когда какой-то счет достигает нуля, удалите его из хэша. Наконец, если две строки являются анаграммами, хэш-таблица в конце будет пустой, иначе она не будет пустой.

    Пара важных заметок: (1) Игнорировать регистр букв и (2) Игнорировать пробел.

    Вот подробный анализ и реализация на С#: Тестирование Если две строки являются анаграммами

    Zoran Horvat
    18 дек. 2013, в 22:20

    Поделиться

    Некоторое другое решение без сортировки.

    public static boolean isAnagram(String s1, String s2){
        //case insensitive anagram
    
        StringBuffer sb = new StringBuffer(s2.toLowerCase());
        for (char c: s1.toLowerCase().toCharArray()){
            if (Character.isLetter(c)){
    
                int index = sb.indexOf(String.valueOf(c));
                if (index == -1){
                    //char does not exist in other s2
                    return false;
                }
                sb.deleteCharAt(index);
            }
        }
        for (char c: sb.toString().toCharArray()){
            //only allow whitespace as left overs
            if (!Character.isWhitespace(c)){
                return false;
            }
        }
        return true;
    }
    

    jmh
    21 апр. 2013, в 00:14

    Поделиться

    Ниже приведено другое решение с использованием меньших переменных. Он использовал временную сложность O (n).

    public static boolean anagram(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
    
        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();
    
        int sum = 0;
        for( int i=0; i<s1.length(); i++) {
            sum += (s1.charAt(i)-0) - (s2.charAt(i)-0);
        }
    
        if ( sum == 0) return true;
    
        return false;
    }
    

    Naresh Dhiman
    21 янв. 2017, в 21:08

    Поделиться

    Вы должны использовать что-то вроде этого:

        for (int i...) {
            isFound = false;
            for (int j...) {
                if (...) {
                    ...
                    isFound = true;
                }
            }
    

    Значение по умолчанию для isFound должно быть ложным. Просто это

    MPogoda
    23 фев. 2013, в 22:54

    Поделиться

    Я написал эту программу в java. Я думаю, что это также может помочь:

    public class Anagram {
        public static void main(String[] args) {
            checkAnagram("listen", "silent");
        }
    
        public static void checkAnagram(String str1, String str2) {
            boolean isAnagram = false;
            str1 = sortStr(str1);
            str2 = sortStr(str2);
            if (str1.equals(str2)) {
                isAnagram = true;
            }
            if (isAnagram) {
                System.out.println("Two strings are anagram");
            } else {
                System.out.println("Two string are not anagram");
            }
    
        }
    
        public static String sortStr(String str) {
            char[] strArr = str.toCharArray();
            for (int i = 0; i < str.length(); i++) {
                for (int j = i + 1; j < str.length(); j++) {
                    if (strArr[i] > strArr[j]) {
                        char temp = strArr[i];
                        strArr[i] = strArr[j];
                        strArr[j] = temp;
                    }
                }
            }
            String output = String.valueOf(strArr);
            return output;
        }
    }
    

    Rahul Sah
    09 июнь 2017, в 12:25

    Поделиться

    checkAnagram("THE END","DET NEH");
    
    public void checkAnagram(String s3, String s4){
    
            if(Arrays.equals(s3.replace(" ","").chars().sorted().toArray(), s4.replace(" ","").chars().sorted().toArray()))
                System.out.println( s3+ " and "+ s4 + " are Anagrams");
            else
                System.out.println("Not Anagrams");
        }
    

    Chiranjeevi
    15 янв. 2017, в 21:28

    Поделиться

     import java.util.Scanner;
    
     public class AnagramTest {
       public static void main(String[] args) {
       System.out.println("Plz Enter Your First String: ");
       Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
       System.out.println("Plz Enter Your Second String: ");
    
         String s2 = sc.nextLine();
        System.out.println(getAnagramString(s1,s2));
    
    }
    public static boolean getAnagramString(String s1,String s2){
       char[] c1 = s1.toCharArray();
       StringBuffer sb = new StringBuffer(s2);
    for(char d: c1){
       int index = sb.indexOf(String.valueOf(d));       
         if(index !=-1){
             sb.deleteCharAt(index);
         }//if
         else{
             return false;
         }
    }
    return sb.length() ==0;
    }
    

    }

    Manash Ranjan Dakua
    23 окт. 2016, в 10:59

    Поделиться

    Работает отлично! Но не очень хороший подход, поскольку он работает в O (n ^ 2)

    boolean isAnagram(String A, String B) {
        if(A.length() != B.length())
            return false;
    
       A = A.toLowerCase();
       B = B.toLowerCase();
    
       for(int i = 0; i < A.length(); i++){
           boolean found = false;
           for(int j = 0; j < B.length(); j++){
               if(A.charAt(i) == B.charAt(j)){
                   found = true;
                   break;
               }
           }
           if(!found){
               return false;
           }
       }
    
       for(int i = 0; i < B.length(); i++){
           boolean found = false;
           for(int j = 0; j < A.length(); j++){
               if(A.charAt(j) == B.charAt(i)){
                   found = true;
                   break;
               }
           }
           if(!found){
               return false;
           }
       }
    
       int sum1 = 0, sum2 = 0;
       for(int i = 0; i < A.length(); i++){
           sum1 += (int)A.charAt(i);
           sum2 += (int)B.charAt(i);               
       }
    
       if(sum1 == sum2){
           return true;
       } 
       return false;
    }
    

    Pradip Kharbuja
    09 март 2016, в 04:44

    Поделиться

    Я знаю, что это старый вопрос. Однако я надеюсь, что это может помочь кому-то. Временной сложностью этого решения является O (n ^ 2).

    public boolean areAnagrams(final String word1, final String word2) {
            if (word1.length() != word2.length())
                return false;
    
            if (word1.equals(word2))
                return true;
    
            if (word1.length() == 0 && word2.length() == 0)
                return true;
    
            String secondWord = word2;
            for (int i = 0; i < word1.length(); i++) {
                if (secondWord.indexOf(word1.charAt(i)) == -1)
                    return false;
    
                secondWord = secondWord.replaceFirst(word1.charAt(i) + "", "");
            }
    
            if (secondWord.length() > 0)
                return false;
    
            return true;
    }
    

    okello
    26 июль 2015, в 01:10

    Поделиться

    public static boolean isAnagram(String str1, String str2) {
        if( str1.length() != str2.length() ) return false;
        int str1Tot = 0;
        int str2Tot = 0;
        for( int i = 0 ; i < str1.length() ; i++) {
            str1Tot += str1.codePointAt(i);
            str2Tot += str2.codePointAt(i);
        }
        if( str1Tot == str2Tot ) return true;
        else return false;      
    }
    

    Venkat
    12 май 2014, в 06:37

    Поделиться

    public class Anagrams {
    
    //Write aprogram to check if two words are anagrams
    public static void main(String[] args) {
        Anagrams an=new Anagrams();
        System.out.println(an.isAnagrams("tree", "eetr"));
    
    }
    
    public boolean isAnagrams(String word1,String word2)
    {
        boolean anagrams=false;
        char []arr1=word1.toCharArray();
        char []arr2=word2.toCharArray();
    
        //They should be the same length
        int sum1=0;
        int sum2=0;
        for(int i=0;i<arr1.length;i++)
        {
            sum1+=(int)arr1[i];
            sum2+=(int)arr2[i];
        }
    
        if(sum1==sum2)
        {
            anagrams=true;
        }
    
        return anagrams;
    }
    

    }

    Output:-
    true
    

    Mokhtar Kalmoush
    21 нояб. 2013, в 17:14

    Поделиться

    Кажется, для такой простой задачи очень неудобно.

    Во-первых,

    Ваши петли слишком сложны. Попробуйте что-то вроде этого.

    public static String lettersOnly(String word) 
    {
        int length = word.length();
        StringBuilder end = new StringBuilder(length);
        char x;
    
        for (int i = (length - 1); i >= 0; i--) {
            x = word.charAt(i);
            if (Character.isLetter(x)) {
                end.append(x);
            }
        }
        return end.toString();
    

    Это гораздо более упрощенный способ проверки, являются ли они анаграммами.

    Вы также можете создать отдельный метод для всей печати, который будет намного проще.

    И, наконец, просто используйте

        String ltrsOnlyOne = lettersOnly(wordOne);
        String ltrsOnlyTwo = lettersOnly(wordTwo);
    

    для создания строк.

    user2108562
    25 фев. 2013, в 20:18

    Поделиться

    У меня есть что-то новое, я попытался выполнить это в O (n) с помощью операций XOR.

    public class TwoStringAnagram {
    
        private static boolean isTwoStringsAnagram(String str1, String str2) {
            if (str1.length() < 2 && str2.length() < 2) return false;
            if (str1.length() != str2.length()) return false;
    
            char[] charStr1 = str1.toCharArray();
            char[] charStr2 = str2.toCharArray();
    
            int xorSum = 0;
            for (int i = 0; i < charStr1.length; i++) {
                xorSum = xorSum ^ charStr1[i] ^ charStr2[i];
            }
            return xorSum == 0;
        }
    
        public static void main(String args[]) {
            String str1 = "ACT";
            String str2 = "TAC";
            System.out.println("Are input strings anagrams? " + isTwoStringsAnagram(str1, str2));
        }
    }
    

    Priyank Shah
    10 дек. 2016, в 11:14

    Поделиться

    Способ решения этого вопроса — на основе ответа Сай Кирана.

    import java.util.Scanner;
    
    public class Anagram {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Enter first word : ");
            String word1 = sc.nextLine();
            System.out.print("Enter second word : ");
            String word2 = sc.nextLine();
    
            sc.close();
    
            System.out.println("Is Anagram : " + isAnagram(word1, word2));
        }
    
        private static boolean isAnagram(String word1, String word2) {
    
            if (word1.length() != word2.length()) {
                System.err.println("Words length didn't match!");
                return false;
            }
    
            char ch1, ch2;
            int len = word1.length(), sumOfWord1Chars = 0, sumOfWord2Chars = 0;
    
            for (int i = 0; i < len; i++) {
                ch1 = word1.charAt(i);
                if (word2.indexOf(ch1) < 0) {
                    System.err.println("'" + ch1 + "' not found in "" + word2
                            + """);
                    return false;
                }
                sumOfWord1Chars += word1.charAt(i);
    
                ch2 = word2.charAt(i);
                if (word1.indexOf(ch2) < 0) {
                    System.err.println("'" + ch2 + "' not found in "" + word1
                            + """);
                    return false;
                }
                sumOfWord2Chars += word2.charAt(i);
            }
    
            if (sumOfWord1Chars != sumOfWord2Chars) {
                System.err
                        .println("Sum of both words didn't match, i.e., words having same characters but with different counts!");
                return false;
            }
    
            return true;
        }
    }
    

    53by97
    26 май 2014, в 10:10

    Поделиться

    public class Anagram {
    
    public static void main(String[] args) {
    
        String s1 = "abcdeaa11 fghijk lmnoAA";
        String s2 = "AAlmno1 edcba1fghijkaa";
        System.out.println(isAnagram(s1, s2));
    }
    
    private static String isAnagram(String s1, String s2) {
    
        char[] array1 = s1.replaceAll("[\s]", "").toLowerCase().toCharArray();
        char[] array2 = s2.replaceAll("[\s]", "").toLowerCase().toCharArray();
        boolean anagram = false;
        List<Character> list = new LinkedList<Character>();
    
        for (int i = 0; i < array1.length; i++) {
            list.add(array1[i]);
        }
        for (int i = 0; i < array2.length; i++) {
            if (list.isEmpty()) {
                break;
            }
            if (list.contains(array2[i]))
                list.remove((Object) array2[i]);
    
            if (i == array1.length - 1 && list.isEmpty())
                anagram = true;
         }
        if (anagram)
            return "The given strings are anagrams";
    
        return "The strings are not anagrams";
    }
    
    }
    

    Sanal Thomas
    08 янв. 2014, в 18:58

    Поделиться

    Ещё вопросы

    • 0Перетащите папки с помощью перетаскиваемых и сбрасываемых функций jquery
    • 0выберите updated_dates, которые не находятся между начатыми датами и остановленными датами
    • 1обработка различных строк валюты панды
    • 1priority-web-sdk: реализация поля выбора
    • 0оператор << и оператор >> перегруженные функции
    • 0Как обнаружить событие нажатия на любой флажок на странице, используя jQuery?
    • 1Android L — Снимайте флеш-изображение с автофокусом, используя Camera2 api
    • 0Исправить ошибку в Amazon PHP SDK
    • 0Критерии гибернации с использованием Group By Hour
    • 0ставить тире после каждого n символов во время ввода с клавиатуры
    • 0Выстрел события при выборе первого варианта выбора элемента
    • 1Найти похожее свойство, затем перебрать объект
    • 1я не понимаю, что такое «защищенная пустота Page_Load»
    • 1Приложение для магазина Windows 8. Посмотреть список. Прокрутка сенсорного элемента и указатель *
    • 1Новый пользователь Maven запрашивает помощь в расшифровке зависимостей для агента openam tomcat 6
    • 1Как построить вызов метода с использованием динамического
    • 0Cookie-проблема в Angular
    • 0Идентификатор звонка в Jquery
    • 0Избегайте повторяющегося конструктора для пользовательских наследуемых классов
    • 0Jquery Validation Engine, отображающий ошибки в предупреждении
    • 1Исправьте класс JOOQ для использования с DSLConext для создания и повторения результата
    • 0Как реализовать показы и отслеживание показов
    • 1Скрытие календаря от DatePicker программно в API 21
    • 0Изображение в масштабе php на основе пользовательского ввода
    • 0Как бы вы запустили очистку после создания исключения в оболочке API?
    • 1Android — Как отфильтровать просмотр списка по нескольким значениям?
    • 0executebatch () в JDBC вставляет только несколько записей
    • 1Передача параметров из одного файла JSP во включенный файл JSP?
    • 1Как подобрать параметр функции tenorflow (python)
    • 0Как мне изменить, куда указывает указатель, передавая его по ссылке?
    • 1чтение и запись нескольких файлов отдельно от консоли Python
    • 0Microsoft Access SQL Query Две таблицы многие к одной
    • 0получить сумму нескольких значений по месяцам в одной таблице
    • 0Один сокет отправляет и получает через интерфейс WLAN и Eth
    • 0PHP не может печатать на сетевой принтер
    • 1сельдерей вложенные аккорды не вызывают обратный вызов в правильном порядке
    • 0компоновка беседки для больших данных
    • 1Преобразовать столбец со списком кортежей во множество столбцов
    • 0Параметр функции «не объявлен в этой области». Параметр виден в файле h
    • 1Потеря времени при конвертации из эпохи
    • 0Класс не добавляется к элементу при нажатии
    • 0Заполнитель ввода не работает с angular и ui.router
    • 0JQuery UI гармошка работает в режиме отладки MVC 4, но не в выпуске
    • 1единичное тестирование метода, который вызывает другой метод
    • 0мобильная версия сайта номер мобильного телефона всегда белого цвета
    • 0Не удается подключиться из докера с помощью mysqlclient
    • 1Как добавить контент javascript на страницу asp.net
    • 1Выполнять действия с задержкой между ними
    • 1Написание JSON-представления графа
    • 1Как добавить «блоки» в платформенную игру на Python, используя pygame?

    Teaching Kids Programming – Check if Word Equals Summation of Two Words

    Teaching Kids Programming: Videos on Data Structures and Algorithms

    The letter value of a letter is its position in the alphabet starting from 0 (i.e. ‘a’ -> 0, ‘b’ -> 1, ‘c’ -> 2, etc.).

    The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.

    For example, if s = “acb”, we concatenate each letter’s letter value, resulting in “021”. After converting it, we get 21.
    You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters ‘a’ through ‘j’ inclusive.

    Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.

    Example 1:
    Input: firstWord = “acb”, secondWord = “cba”, targetWord = “cdb”
    Output: true
    Explanation:
    The numerical value of firstWord is “acb” -> “021” -> 21.
    The numerical value of secondWord is “cba” -> “210” -> 210.
    The numerical value of targetWord is “cdb” -> “231” -> 231.
    We return true because 21 + 210 == 231.

    Example 2:
    Input: firstWord = “aaa”, secondWord = “a”, targetWord = “aab”
    Output: false
    Explanation:
    The numerical value of firstWord is “aaa” -> “000” -> 0.
    The numerical value of secondWord is “a” -> “0” -> 0.
    The numerical value of targetWord is “aab” -> “001” -> 1.
    We return false because 0 + 0 != 1.

    Example 3:
    Input: firstWord = “aaa”, secondWord = “a”, targetWord = “aaaa”
    Output: true
    Explanation:
    The numerical value of firstWord is “aaa” -> “000” -> 0.
    The numerical value of secondWord is “a” -> “0” -> 0.
    The numerical value of targetWord is “aaaa” -> “0000” -> 0.
    We return true because 0 + 0 == 0.

    Constraints:
    1 <= firstWord.length, secondWord.length, targetWord.length <= 8
    firstWord, secondWord, and targetWord consist of lowercase English letters from ‘a’ to ‘j’ inclusive.

    Hints:
    Convert each character of each word to its numerical value.
    Check if the numerical values satisfies the condition.

    Convert Letters to Numbers

    We can construct the numerical string by the mapping, and then convert it back to base 10 integer.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    class Solution:
        def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:        
            def f(s):
                g = {
                    'a': 0,
                    'b': 1,
                    'c': 2,
                    'd': 3,
                    'e': 4,
                    'f': 5,
                    'g': 6,
                    'h': 7,
                    'i': 8,
                    'j': 9
                }
                a = ""
                for i in s:
                    a += str(g[i])
                return int(a)
            return f(firstWord) + f(secondWord) == f(targetWord)
    class Solution:
        def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:        
            def f(s):
                g = {
                    'a': 0,
                    'b': 1,
                    'c': 2,
                    'd': 3,
                    'e': 4,
                    'f': 5,
                    'g': 6,
                    'h': 7,
                    'i': 8,
                    'j': 9
                }
                a = ""
                for i in s:
                    a += str(g[i])
                return int(a)
            return f(firstWord) + f(secondWord) == f(targetWord)

    Time complexity is O(N) and space complexity is O(N) as we keep the new numerical string. N is the number of the characters in the original words.

    Alternatively, we can go through each character and update the decimal value along the way as we are converting to base 10:

    1
    2
    3
    4
    5
    6
    7
    8
    
    class Solution:
        def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
            def f(s):
                a = 0
                for i in s:
                    a = a * 10 + ord(i) - 97
                return a
            return f(firstWord) + f(secondWord) == f(targetWord)
    class Solution:
        def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
            def f(s):
                a = 0
                for i in s:
                    a = a * 10 + ord(i) - 97
                return a
            return f(firstWord) + f(secondWord) == f(targetWord)

    Time complexity is O(N) and space complexity is O(1).

    –EOF (The Ultimate Computing & Technology Blog) —

    GD Star Rating
    loading…

    633 words
    Last Post: GoLang: Sign of the Product of an Array
    Next Post: GoLang: Insert into a Binary Search Tree via Recursion

    The Permanent URL is: Teaching Kids Programming – Check if Word Equals Summation of Two Words (AMP Version)

    Понравилась статья? Поделить с друзьями:
  • Two words combined to make one word
  • Two words combined new word
  • Two words combined into one word
  • Two words become one word
  • Two word verbs with meaning and sentence