如果我使用它,请忽略字母索引
Ignore index of a letter if I use it
我正在研究密钥柱状转置密码,
for(int i = 0; i < column; i++){
position = keyWord.indexOf(sorted_key[i]); // Here's the problem
for(int j = 0; j < row; j++){
matrix[j][position] = cipher_array[count];
count++; }}
关键字是:
analyst
sorted_key 是:
{a, a, l, n, s, t, y}
当我尝试打印变量位置时:
0 0 3 1 5 6 4
但我应该得到这个:
0 2 3 1 5 6 4
当我在密钥中有重复的字母时出现问题。 'a' 在这个例子中,它总是看到它出现的第一个索引,即使它有第二次或第三次出现。如何解决?
您可以维护一个 Map
来保存每个字符的最后一个索引:
Map<Character,Integer> indices = new HashMap<>();
for(int i = 0; i < column; i++) {
// get the previous position of sorted_key[i] (or -1 is there is no previous position)
int last = indices.computeIfAbsent(sorted_key[i],c->-1);
// search for the next position of sorted_key[i]
position = keyWord.indexOf(sorted_key[i],last+1);
// store the next position in the map
indices.put(sorted_key[i],position);
for(int j = 0; j < row; j++) {
matrix[j][position] = cipher_array[count];
count++;
}
}
我正在研究密钥柱状转置密码,
for(int i = 0; i < column; i++){
position = keyWord.indexOf(sorted_key[i]); // Here's the problem
for(int j = 0; j < row; j++){
matrix[j][position] = cipher_array[count];
count++; }}
关键字是:
analyst
sorted_key 是:
{a, a, l, n, s, t, y}
当我尝试打印变量位置时:
0 0 3 1 5 6 4
但我应该得到这个:
0 2 3 1 5 6 4
当我在密钥中有重复的字母时出现问题。 'a' 在这个例子中,它总是看到它出现的第一个索引,即使它有第二次或第三次出现。如何解决?
您可以维护一个 Map
来保存每个字符的最后一个索引:
Map<Character,Integer> indices = new HashMap<>();
for(int i = 0; i < column; i++) {
// get the previous position of sorted_key[i] (or -1 is there is no previous position)
int last = indices.computeIfAbsent(sorted_key[i],c->-1);
// search for the next position of sorted_key[i]
position = keyWord.indexOf(sorted_key[i],last+1);
// store the next position in the map
indices.put(sorted_key[i],position);
for(int j = 0; j < row; j++) {
matrix[j][position] = cipher_array[count];
count++;
}
}