Problem Statement | |||||||||||||
A square matrix is a grid of NxN numbers. For example, the following is a 3x3 matrix: 4 3 5 2 4 5 0 1 9One way to represent a matrix of numbers, each of which is between 0 and 9 inclusive, is as a row-major String. To generate the String, simply concatenate all of the elements from the first row followed by the second row and so on, without any spaces. For example, the above matrix would be represented as "435245019". You will be given a square matrix as a row-major String. Your task is to convert it into a String[], where each element represents one row of the original matrix. Element i of the String[] represents row i of the matrix. You should not include any spaces in your return. Hence, for the above String, you would return {"435","245","019"}. If the input does not represent a square matrix because the number of characters is not a perfect square, return an empty String[], {}. | |||||||||||||
Definition | |||||||||||||
| |||||||||||||
public class MatrixTool
{
public String[] convert(String str)
{
String[] matrix = null;
if(str==null || str.length()<1)
{
return matrix;
}
int total = str.length();
double d = total/1.0;
int len = (int)Math.sqrt(d);
//check
for(int i=0;i<total;i++)
{
if(str.charAt(i)>='0' && str.charAt(i)<='9')
{
}
else
{
System.out.println("invaid charareter.");
return matrix;
}
}
if(len*len == total)
{
matrix = new String[len];
for(int i=0;i<len;i++)
{
matrix[i] = "";
for(int j=0;j<len;j++)
{
matrix[i]+= str.charAt(i*len+j);
}
}
}
return matrix;
}
public static void main(String args[]){
MatrixTool mt = new MatrixTool();
String[] temp = mt.convert("435245019");
for(int i=0;i<temp.length;i++){
System.out.println(temp[i]);
}
}
}
博客展示了一段Java代码,定义了MatrixTool类,其中convert方法用于将字符串转换为矩阵。代码会检查字符串长度是否为完全平方数,且字符是否为数字,若符合条件则进行转换。最后在main方法中调用convert方法并输出结果。
4406

被折叠的 条评论
为什么被折叠?



