Sort String According to Order Defined by Pattern String

package org.wesome.dsalgo;

import java.util.Arrays;

public class SortStringByPattern {

    static char[] sortStringByPattern(String string, String pattern) {
        final int NinetySeven = 'a';
        System.out.println("ascii value of a is  = " + (int) 'a');
        char[] stringArr = string.toCharArray();
        char[] patternArr = pattern.toCharArray();
        int freq[] = new int[26];
        for (int i = 0; i < string.length(); i++) {
            freq[stringArr[i] - NinetySeven]++;
        }
        int index = 0;
        for (int i = 0; i < pattern.length(); i++) {
            for (int j = 0; j < freq[patternArr[i] - NinetySeven]; j++) {
                stringArr[index] = patternArr[i];
                index++;
            }
        }
        System.out.println(Arrays.toString(stringArr));
        return stringArr;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.SortStringByPattern.sortStringByPattern;

public class SortStringByPatternTest {
    @Test
    void SortStringByPatternTest1() {
        String string = "wesome";
        String pattern = "wsm";
        Assertions.assertArrayEquals(new char[]{'w', 's', 'm', 'o', 'm', 'e'}, sortStringByPattern(string, pattern));
    }

    @Test
    void SortStringByPatternTest2() {
        String string = "dsalgofromwesomeorg";
        String pattern = "msw";
        Assertions.assertArrayEquals(new char[]{'m', 'm', 's', 's', 'w', 'o', 'f', 'r', 'o', 'm', 'w', 'e', 's', 'o', 'm', 'e', 'o', 'r', 'g'}, sortStringByPattern(string, pattern));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on