Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4d24b2e

Browse files
committed
reverse word
1 parent562bc62 commit4d24b2e

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

‎array/SpiralOrder_1201.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
packageAlgorithms.array;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.List;
5+
6+
publicclassSpiralOrder_1201 {
7+
publicList<Integer>spiralOrder(int[][]matrix) {
8+
List<Integer>ret =newArrayList<Integer>();
9+
if (matrix ==null ||matrix.length ==0) {
10+
// 注意在非法的时候,应该返回空解,而不是一个NULL值
11+
returnret;
12+
}
13+
14+
// Record how many rows and cols we still have.
15+
introws =matrix.length;
16+
intcols =matrix[0].length;
17+
18+
// The four coners.
19+
inttop =0;
20+
intleft =0;
21+
intbottom =rows -1;
22+
intright =cols -1;
23+
24+
// every time we go through two rows and two cols.
25+
for (;rows >0 &&cols >0;rows -=2,cols -=2,top++,left++,bottom--,right--) {
26+
// the first line.
27+
for (inti =left;i <=right;i++) {
28+
ret.add(matrix[top][i]);
29+
}
30+
31+
// the right column.
32+
for (inti =top +1;i <bottom;i++) {
33+
ret.add(matrix[i][right]);
34+
}
35+
36+
// the down line;
37+
if (rows >1) {
38+
for (intj =right;j >=left;j--) {
39+
ret.add(matrix[bottom][j]);
40+
}
41+
}
42+
43+
// the left column.
44+
if (cols >1) {
45+
for (inti =bottom -1;i >top;i --) {
46+
ret.add(matrix[i][left]);
47+
}
48+
}
49+
}
50+
51+
returnret;
52+
}
53+
}

‎string/ReverseWords.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
packageAlgorithms.string;
2+
3+
publicclassReverseWords {
4+
publicstaticvoidmain(String[]strs) {
5+
reverseWords(" I love cmu ");
6+
}
7+
8+
/**
9+
* @param s : A string
10+
* @return : A string
11+
*/
12+
publicstaticStringreverseWords(Strings) {
13+
// write your code
14+
if (s ==null) {
15+
returnnull;
16+
}
17+
18+
StringBuildersb =newStringBuilder();
19+
20+
// remove the leading and the tail space.
21+
//String sTrim = s.trim();
22+
String[]strs =s.split("\\s+");
23+
for (inti =strs.length -1;i >=0;i--) {
24+
System.out.println("word:" +strs[i]);
25+
if (strs[i].equals("")) {
26+
continue;
27+
}
28+
29+
sb.append(strs[i]);
30+
if (i !=0) {
31+
sb.append(" ");
32+
}
33+
}
34+
35+
returnsb.toString();
36+
}
37+
}
38+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp