Algorithm-String
通过翻转来位移
-
字符串
public class LeftShift { void StringReverse(char[] strs, int start, int end) { char tmp; while (end > start) { tmp = strs[start]; strs[start++] = strs[end]; strs[end--] = tmp; } } public String stringShiftLeft(String str, int m) { char[] strs = str.toCharArray(); m %= str.length(); StringReverse(strs, 0, m - 1); StringReverse(strs, m, str.length() - 1); StringReverse(strs, 0, str.length() - 1); return new String(strs); }
-
链表
Node listReverse(Node root, int start, int end) { Node head = new Node(0); head.next = root; Node pre = head; for (int i = 0; i < start - 1; i++) { pre = pre.next; } Node node = pre.next; Node post = node.next; for (int i = 0; i < end - start; i++) { node.next = post.next; post.next = pre.next; pre.next = post; post = node.next; } return head.next; } public Node listRotate(Node root, int walk) { Node node = root; int len = 0; while (node != null) { len++; node = node.next; } root = listReverse(root, 1, walk); root = listReverse(root, walk + 1, len); return root; }
26个字目HASH
boolean stringContain(String str1, String str2) {
int hash = 0;
String str = str1.toUpperCase();
for (int i = 0; i < str.length(); i++) {
hash |= (1 << (str.charAt(i) - 'A'));
}
str = str2.toUpperCase();
for (int i = 0; i < str2.length(); i++) {
if ((hash & (1 << (str.charAt(i) - 'A'))) == 0) {
return false;
}
}
return true;
}
String To Integer
// sign must be initialized,may be some value not contains '+', which means '+'
int sign = 1, digit, index = 0, total = 0;
//empty string
if (str.length() == 0) {
return 0;
}
//remove space, should not to use trim
while (index < str.length() && str.charAt(index) == ' ') {
index++;
}
//handle sign
if (str.charAt(index) == '+' || str.charAt(index) == '-') {
sign = str.charAt(index) == '+' ? 1 : -1;
index++;
}
//convert string to number
while (index < str.length()) {
digit = str.charAt(index++) - '0';
//exception
if (digit < 0 || digit > 9) {
break;
}
//avoid overflow
if (total > Integer.MAX_VALUE / 10 || total == Integer.MAX_VALUE / 10 && digit > 7) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
total = total * 10 + digit;
}
return total * sign;
test case
@RunWith(Parameterized.class)
public class StringToIntegerTest {
private StringToInteger solution;
@Parameter
public String input;
@Parameter(1)
public int output;
public static final Object[][] test = {
{"1230", 1230},
{"123", 123},
{"-321809", -321809},
{"+", 0},
{"-", 0},
{"+12309", 12309},
{"-1239", -1239},
{"123a76", 123},
{"12345678987654321",Integer.MAX_VALUE},
{"-12345678987654321",Integer.MIN_VALUE}
};
@Parameters(name = "{index}")
public static Iterable<Object[]> tests() {
return Arrays.asList(test);
}
@Before
public void setUp() throws Exception {
solution = new StringToInteger();
}
@Test
public void strToInt() throws Exception {
assertThat(solution.StrToInt(input), is(output));
}
}