如何在矩阵中查找单词,其中每个字符都在唯一的行上

时间:2018-12-28 20:55:40

标签: algorithm matrix

例如:

row1 [ a y e m a ]
row2 [ l i t a p ]
row3 [ i y n a t ]

现在单词'may'成为可能,因为'm'在第1行,'a'在第2行,'y'在第'3'行

但是,由于i和t具有相同的行,所以不可能使用'tin'。

注意:输入字符不必按行顺序。 tin也可以像输入一样为int。假设字符数与矩阵中的行数相同。

简化版本: 假设输入单词中没有字符重复(例如:五月,锡)

复杂版本: 字符可以重复:(例如:tat)

2 个答案:

答案 0 :(得分:0)

伪代码中的算法为:

row1 [ a y e m a ]
row2 [ l i t a p ]
row3 [ i y n a t ]
key = 'may'
x = 1

while (x < N) do
  if (key[x] not in rowx) then
     return 'Not found'
  endif else then
     x = x + 1
  endelse
done 
return 'Found'

答案 1 :(得分:0)

    // row1 [ a y e m a ]
// row2 [ l i t a p ]
// row3 [ i y n a t ]
//i would try to remap your data to something like
var data  = new List<char>[255];

for(var i in in rows){
    for(for j in rows[i]){
        var ch =rows[i][j]// a,b,c,d 
        if(data[ch]==null){
            data[ch] = new List<int>()
        }

        data[ch].add(i); // fill in row numbers here for every character
    }
}
// you will have an array were you can find any character in constant time O(1)
[a] = [row1, row2,row3, row1];
[b] = null;
[m] = [row1]
[y] = [row1,row3]
[t] = row3
[i] = row2
[n] = row3

//after you can try to find all rownumbers and check for uniquiness
var hs = new HashSet<int>();
hs.addAll(data[m]);
hs.addAll(data[a]);
hs.addAll(data[y]);
//in C# hs will contain only unique values
hs = [row1, row2,row3]
return hs.length>="may".length;

//instead of hashset we can use groupby for cases like tat, taa etc.