-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL1163.java
More file actions
96 lines (76 loc) · 2.13 KB
/
L1163.java
File metadata and controls
96 lines (76 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.liang.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName L1163
* @description last-substring-in-lexicographical-order 按字典排序最后的字串
* @Author LiaNg
* @Date 2019-08-23
*/
public class L1163 {
public static void main(String[] args) {
String s = "world";
System.out.println("lastSubstring(s) = " + lastSubstring(s));
}
private static String lastSubstring(String s) {
if (s == null || s.length() <= 1) {
return s;
}
char[] sChars = s.toCharArray();
int index = 0;
char max = 'a';
char sam = s.charAt(0);
boolean same = true;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) != sam) {
same = false;
break;
}
}
if (same) {
return s;
}
for (char sChar : sChars) {
if ((sChar - 'a') > index) {
index = sChar - 'a';
max = sChar;
}
}
List<Node> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == max) {
list.add((new Node(i, i)));
}
}
if (list.size() == 1) {
return s.substring(list.get(0).index);
}
while (true) {
char x = 'a';
for (Node n : list) {
n.temp += 1;
if (n.temp < s.length() && s.charAt(n.temp) > x) {
x = s.charAt(n.temp);
}
}
List<Node> newList = new ArrayList<>();
for (Node n : list) {
if (n.temp < s.length() && s.charAt(n.temp) == x) {
newList.add(n);
}
}
if (newList.size() == 1) {
return s.substring(newList.get(0).index);
}
list = newList;
}
}
static class Node{
int temp;
int index;
Node(int temp, int index) {
this.temp = temp;
this.index = index;
}
}
}