返回整数,对应于用于形成混乱字符串的数字。整数必须按升序排序。

huangapple go评论65阅读模式
英文:

Write a program that returns integers corresponding to the numerals used to form the jumbled string. Integers must be sorted in ascending order

问题

在JP Morgan的问题中,要求编写一个程序,将给定的字符串中的混乱字母重新排序,形成由数字零到九组成的单词。每个数字可以在混乱的字符串中出现多次。编写程序以按升序返回形成混乱字符串的数字。

例如,"reuonnoinfe" 是字符串中混乱的字母,可以重新排列为 "one four nine",因此程序的输出应该是 "149"。

以下是您提供的Java代码的翻译部分:

package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        String line = "reuonnoinfe";
        String constNum = "zero,one,two,three,four,five,six,seven,eight,nine";
        List<String> subStringList = subString(line, line.length());
        System.out.println(calculateNumber(constNum, subStringList));
    }

    private static List<String> subString(String str, int n) {

        List<String> retString = new ArrayList<>();
        String tempStr;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j <= n; j++) {
                tempStr = str.substring(i, j);
                if (null != tempStr && tempStr.length() > 2 && tempStr.length() < 4) {
                    retString.add(tempStr.toLowerCase());
                }
            }
        }
        return retString;
    }

    private static String calculateNumber(String stringConst, List<String> subStringList) {

        StringBuilder strb = new StringBuilder();
        stringConst = "one";
        String[] str = stringConst.split(",");
        int cnt = 0;
        for (String obj : str) {
            for (String objSubString : subStringList) {
                if (areAnagram(obj.toCharArray(), objSubString.toCharArray())) {
                    strb.append(cnt + "");
                }
            }
            cnt++;
        }

        return strb.toString();
    }

    private static boolean areAnagram(char str1[], char str2[]) {
        int NO_OF_CHARS = 256;
        int count1[] = new int[NO_OF_CHARS];
        Arrays.fill(count1, 0);
        int count2[] = new int[NO_OF_CHARS];
        Arrays.fill(count2, 0);
        int i;

        for (i = 0; i < str1.length && i < str2.length; i++) {
            count1[str1[i]]++;
            count2[str2[i]]++;
        }

        if (str1.length != str2.length)
            return false;

        for (i = 0; i < NO_OF_CHARS; i++)
            if (count1[i] != count2[i])
                return false;

        return true;
    }
}

请注意,这段代码中有一些问题,需要修复才能得到正确的结果。

英文:

Asked in JP Morgan:
You are given a string containing jumbled letters from several concatenated words. Each word is a numeral from zero to nine. Each numeral may be used multiple times in the jumbled string.

Write a program that returns integers corresponding to the numerals used to form the jumbled string. Integers must be sorted in ascending order.

For example, reuonnoinfe are shuffled letters of the strings one four nine. Your program's output should be 149.
Input:

A string formed from jumbled letters of numerals. For example:

reuonnoinfe

Output:

A sequence of integers used to form the string in ascending order. For example:

149

I tried solving but could not solve it. Below is my solution but it's not working. It will be great if someone can provide a solution in java.

package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String line = &quot;reuonnoinfe&quot;;
String constNum = &quot;zero,one,two,three,four,five,six,seven,eight,nine&quot;;
List&lt;String&gt; subStringList = subString(line, line.length());
System.out.println(calculateNumber(constNum, subStringList));
}
// To find all the substring from given string with length &gt; 3 and &lt;6
private static List&lt;String&gt; subString(String str, int n) {
List&lt;String&gt; retString = new ArrayList&lt;&gt;();
String tempStr;
// Pick starting point
for (int i = 0; i &lt; n; i++) {
// Pick ending point
for (int j = i + 1; j &lt;= n; j++) {
// Print characters from current
// starting point to current ending
// point.
tempStr = str.substring(i, j);
if (null != tempStr &amp;&amp; tempStr.length() &gt; 2 &amp;&amp; tempStr.length() &lt; 4) {
retString.add(tempStr.toLowerCase());
}
}
}
return retString;
}
// find all the substring which are anagrams of one the number String.
private static String calculateNumber(String stringConst, List&lt;String&gt; subStringList) {
StringBuilder strb = new StringBuilder();
stringConst = &quot;one&quot;;
String[] str = stringConst.split(&quot;,&quot;);
int cnt = 0;
for (String obj : str) {
for (String objSubString : subStringList) {
if (areAnagram(obj.toCharArray(), objSubString.toCharArray())) {
strb.append(cnt + &quot;&quot;);
}
}
cnt++;
}
return strb.toString();
}
// find two string are angram
private static boolean areAnagram(char str1[], char str2[]) {
int NO_OF_CHARS = 256;
// Create 2 count arrays and initialize
// all values as 0
int count1[] = new int[NO_OF_CHARS];
Arrays.fill(count1, 0);
int count2[] = new int[NO_OF_CHARS];
Arrays.fill(count2, 0);
int i;
// For each character in input strings,
// increment count in the corresponding
// count array
for (i = 0; i &lt; str1.length &amp;&amp; i &lt; str2.length; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
// If both strings are of different length.
// Removing this condition will make the program
// fail for strings like &quot;aaca&quot; and &quot;aca&quot;
if (str1.length != str2.length)
return false;
// Compare count arrays
for (i = 0; i &lt; NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
}

答案1

得分: 3

看起来你知道如何创建带有字符出现次数计数(count1, count2)的数组 - 这对于计数方法非常关键。

编辑 第一次尝试受到“破坏性”组合的影响(“one”从“four + seven”等处窃取字符),正如Ole V.V.所指出的

如果没有多余的字符,我们可以按特定顺序遍历样本数组:首先是偶数索引(所有这些单词都包含唯一字符,如“zero”中的“z”),然后是奇数索引,最后排序结果(或生成两个单独的字符串并合并它们)

伪代码概述:

创建示例字符串数组或列表 A[0] = "zero" 等
创建字符串 "reuonnoinfe" 的字符计数数组 c1
for (int i = 0; i < 10; i += 2)
     创建字符串 A[i] 的字符计数数组 c2
     当 c2 的所有非零元素都小于或等于对应的 c1 元素时:
          将 i(索引!)添加到输出
          递减 c1[] 由 c2[]
          // 如果 c1 变为全零,我们可以在这里停止
for (int i = 1; i < 10; i += 2)
     创建字符串 A[i] 的字符计数数组 c2
     当 c2 的所有非零元素都小于或等于对应的 c1 元素时:
          将 i(索引!)添加到输出
          递减 c1[] 由 c2[]
排序输出

一些输出示例(快速创建的Delphi代码ideone):

eightnineoneonefoureightsixfivesevenseven
otfoenfueeseiiivsngrenthnevhxineogeneiesv
1145677889
onethreeseven
eeetnhvreones
137
eighttwozerosixfourninesixninesevensix
evhionfxietnnnozgieeourwxrsetsiisxnesi
0246667899
twosixtwoninesevenfoureightninezerosix
onfsntweeieitsixegxtozhinnersonvrwuioe
0224667899
zerofouronefoureightninefiveseven
srnfneriouiheeeovurevtifeofngneoz
01445789
threethreefivesevenonezerofoureightfour
tunorheeierthorgvoeeuzeffnerfreeveoihts
013344578
fiveonezeroseventhreesevenfoureight
netoseeeefrieotnernorfheugevseizvvh
01345778
fiveseventwo
fnewtveeosvi
257
英文:

Seems you know how to create array with char occurence count (count1, count2) - this is key for counting approach.

Edit the first try suffers from "breaking" combination(s) ("one" steals chars from "four + seven" etc) as Ole V.V. noticed

If we have no excessive chars, we can traverse sample array is special order: at first even indices (all these words contain unique chars like "z" in "zero"), then odd ones, and finally sort result (or generate two separate strings and merge them)

Pseudocode outline:

create array or list of sample strings A[0] = &quot;zero&quot; etc
create char count array for string &quot;reuonnoinfe&quot; c1
for (int i = 0; i &lt; 10; i += 2)
create char count array c2 for A[i]
while ALL non-zero elements of c2 are &lt;= than corresponding c1 elements:
add  i (index!) to output
decrement c1[] by c2[]
// we can stop here if c1 becomes all-zero  
for (int i = 1; i &lt; 10; i += 2)
create char count array c2 for A[i]
while ALL non-zero elements of c2 are &lt;= than corresponding c1 elements:
add  i (index!) to output
decrement c1[] by c2[]
sort output 

Some examples of output (quick-made Delphi code ideone):

eightnineoneonefoureightsixfivesevenseven
otfoenfueeseiiivsngrenthnevhxineogeneiesv
1145677889
onethreeseven
eeetnhvreones
137
eighttwozerosixfourninesixninesevensix
evhionfxietnnnozgieeourwxrsetsiisxnesi
0246667899
twosixtwoninesevenfoureightninezerosix
onfsntweeieitsixegxtozhinnersonvrwuioe
0224667899
zerofouronefoureightninefiveseven
srnfneriouiheeeovurevtifeofngneoz
01445789
threethreefivesevenonezerofoureightfour
tunorheeierthorgvoeeuzeffnerfreeveoihts
013344578
fiveonezeroseventhreesevenfoureight
netoseeeefrieotnernorfheugevseizvvh
01345778
fiveseventwo
fnewtveeosvi
257

huangapple
  • 本文由 发表于 2020年7月22日 14:12:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63027987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定